【Sudoku Solver】cpp
题目:
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
代码:
class Solution {
public:
void solveSudoku(vector<vector<char> >& board)
{
vector<pair<int, int> > emptyCells;
vector<set<char> > rowSet, colSet, matrixSet;
set<char> row, col, matrix;
for ( size_t i = ; i < ; ++i )
{
row.clear(); col.clear(); matrix.clear();
for ( size_t j = ; j < ; ++j )
{
if (board[i][j]!='.'){
row.insert(board[i][j]);
}
else{
emptyCells.push_back(make_pair(i, j));
}
if (board[j][i]!='.') col.insert(board[j][i]);
int r = j/+(i/)*, c = j%+(i%)*;
if (board[r][c]!='.') matrix.insert(board[r][c]);
}
rowSet.push_back(row); colSet.push_back(col); matrixSet.push_back(matrix);
}
Solution::dfs(board, emptyCells, rowSet, colSet, matrixSet);
}
static bool dfs(
vector<vector<char> >& board,
vector<pair<int, int> >& emptyCell,
vector<set<char> >& rowSet,
vector<set<char> >& colSet,
vector<set<char> >& matrixSet)
{
if ( emptyCell.empty() ) return true;
int i = emptyCell.back().first;
int j = emptyCell.back().second;
for ( char v = ''; v<='' && !emptyCell.empty(); ++v )
{
if (rowSet[i].find(v)==rowSet[i].end() &&
colSet[j].find(v)==colSet[j].end() &&
matrixSet[(i/)*+j/].find(v)==matrixSet[(i/)*+j/].end() )
{
board[i][j]=v;
rowSet[i].insert(v);
colSet[j].insert(v);
matrixSet[(i/)*+j/].insert(v);
emptyCell.pop_back();
if ( Solution::dfs(board, emptyCell, rowSet, colSet, matrixSet) )
{
return true;
}
else
{
emptyCell.push_back(make_pair(i, j));
board[i][j] = '.';
rowSet[i].erase(v);
colSet[j].erase(v);
matrixSet[(i/)*+j/].erase(v);
}
}
}
return false;
}
};
tips:
采用深搜模板。
主要思路走一遍board,得到三个set,一个vector
1. 三个set分别为每行、列、子模块已有的数字
2. 一个vector中存放着'.'的位置
每次处理一个'.',遍历1到9:
1. 如果满足数独的条件,就往下走一层
2. 如果1到9都不满足,则退回到上一层,重新选择上一个位置的元素
这里有一个思维陷阱:
emptyCell.pop_back();
if ( Solution::dfs(board, emptyCell, rowSet, colSet, matrixSet) )
{
return true;
}
else
{
emptyCell.push_back(make_pair(i, j));
board[i][j] = '.';
rowSet[i].erase(v);
colSet[j].erase(v);
matrixSet[(i/)*+j/].erase(v);
}
注意:pop和push操作应该是对应的,之前一直以为可以不用push的操作,原因是忽略了一种情况:如果一个位置从1到9都不满足,那么必然要回溯到上一层;即,某一个位置的元素是可能遍历不止一次1到9的。
=================================
这里set的效率可能有些低,换一个hashmap的效率可能高一些。
class Solution {
public:
void solveSudoku(vector<vector<char> >& board)
{
vector<pair<int, int> > emptyCells;
vector<map<char,bool> > rowSet, colSet, matrixSet;
map<char,bool> row, col, matrix;
for ( size_t i = ; i < ; ++i )
{
for ( char v = '' ; v <= ''; ++v ) { row[v] = col[v] = matrix[v] = false; }
for ( size_t j = ; j < ; ++j )
{
if (board[i][j]!='.'){
row[board[i][j]] = true;
}
else{
emptyCells.push_back(make_pair(i, j));
}
if (board[j][i]!='.') col[board[j][i]]=true;
int r = j/+(i/)*, c = j%+(i%)*;
if (board[r][c]!='.') matrix[board[r][c]]=true;
}
rowSet.push_back(row); colSet.push_back(col); matrixSet.push_back(matrix);
}
Solution::dfs(board, emptyCells, rowSet, colSet, matrixSet);
}
static bool dfs(
vector<vector<char> >& board,
vector<pair<int, int> >& emptyCell,
vector<map<char,bool> >& rowSet,
vector<map<char,bool> >& colSet,
vector<map<char,bool> >& matrixSet)
{
if ( emptyCell.empty() ) return true;
int i = emptyCell.back().first, j = emptyCell.back().second;
for ( char v = ''; v<=''; ++v )
{
if (!rowSet[i][v] && !colSet[j][v] && !matrixSet[(i/)*+j/][v] )
{
board[i][j] = v;
rowSet[i][v] = colSet[j][v] = matrixSet[(i/)*+j/][v] = true;
emptyCell.pop_back();
if ( Solution::dfs(board, emptyCell, rowSet, colSet, matrixSet) ){
return true;
}
else{
emptyCell.push_back(make_pair(i, j));
rowSet[i][v] = colSet[j][v] = matrixSet[(i/)*+j/][v] = false;
}
}
}
return false;
}
};
tips:都换成了hashmap,效率有所提升。
============================================
第二次过这道题,还是sub board那块内容调了几次,AC了。
class Solution {
public:
void solveSudoku(vector<vector<char> >& board)
{
// restore all blank positions
vector<pair<int, int> > blanks;
for ( int i=; i<board.size(); ++i )
{
for ( int j=; j<board[i].size(); ++j )
{
if ( board[i][j]=='.' ) blanks.push_back(make_pair(i, j));
}
}
Solution::dfs(board, blanks);
}
static bool dfs(
vector<vector<char> >& board,
vector<pair<int,int> >& blanks )
{
if ( blanks.empty() ) return true;
const int r = blanks.back().first;
const int c = blanks.back().second;
for ( char v=''; v<=''; ++v )
{
bool valid = true;
// check row & column & subBoard
for ( int i=; i<; ++i )
{
if ( board[r][i]==v || board[i][c]==v || board[i/3+(r/3)*3][i%3+(c/3)*3]==v )
{
valid = false;
break;
}
}
if ( valid )
{
board[r][c] = v;
blanks.pop_back();
if ( Solution::dfs(board, blanks) ) return true;
blanks.push_back(make_pair(r, c));
board[r][c] = '.';
}
}
return false;
}
};
【Sudoku Solver】cpp的更多相关文章
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- Hdu 4734 【数位DP】.cpp
题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...
- 【Permutations II】cpp
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
- 【Subsets II】cpp
题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...
- 【Sort Colors】cpp
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
- 【Sort List】cpp
题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...
- 【Path Sum】cpp
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- 【Symmetric Tree】cpp
题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...
- 【Same Tree】cpp
题目: Given two binary trees, write a function to check if they are equal or not. Two binary trees are ...
随机推荐
- LAMP stack-5.6.22 (OpenLogic CentOS 7.2)
平台: CentOS 类型: 虚拟机镜像 软件包: apache2.4.20 mysql5.6.30 php5.6.22 apache application server basic softwar ...
- window下安装scala搭载Intellij IDE
最近由于公司业务需求,要用到scala,编写还是windows下较好,linux下运行比较靠谱,废话少说,直接上步骤! 1.首先安装java环境 jdk下载地址:http://www.oracle.c ...
- 谷歌chrome://chrome-urls/
查看DNS解析时间 1 chrome://dns/ 查看DNS解析的地址 1 chrome://net-internals/#dns 更多功能请参考 1 chrome://chrome-urls/ 以 ...
- 在一个css文件中引入其他css文件
@import "./main.css";@import "./color-dark.css";@import "./reset.css";
- java +selenuim使用js显示控件
操作selenium控件时,往往需要有些控件提前显示,特别是后台的一些控件,或者需要使用鼠标显示下拉的操作,有时鼠标悬停,在点击不怎么好使,就可以依靠js方式,提前让控件显示. 1.使用style的方 ...
- Trie:字典树
简介 \(Trie\),又称字典树或前缀树,是一种有序树状的数据结构,用于保存关联数组,其中的键值通常是字符串. 作用 把许多字符串做成一个字符串集合,并可以对其进行快速查找(本文以求多少个单词是一个 ...
- SC || 记不住的正则
+表示一个或多个 *表示零个或多个 ?表示零个或一个 {n} 表示n次 {n,m}表示[n, m]次 {,n}==[0,n] {m,}==[m,INT_MAX] \d 一个数字 \D 一个非数字 \ ...
- javaweb基础(32)_jdbc学习入门
一.JDBC相关概念介绍 1.1.数据库驱动 这里的驱动的概念和平时听到的那种驱动的概念是一样的,比如平时购买的声卡,网卡直接插到计算机上面是不能用的,必须要安装相应的驱动程序之后才能够使用声卡和网卡 ...
- R+hadoop
这里面的配置 http://www.rdatamining.com/big-data/r-hadoop-setup-guide root@kali:~/hadoop_home/hadoop-1.2.1 ...
- WP Mail SMTP插件解决Contact Form 7表单提交失败问题
WP Mail SMTP插件解决Contact Form 7表单提交失败问题 WP Mail SMTP是一款非常优秀的解决WordPress主机因为不支持或者是禁用了mail()函数,导致无法实现在线 ...