【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 ...
随机推荐
- 跨平台移动开发phonegap/cordova 3.3全系列教程-结合asp.net/jqmboile
遠程app配置 把編譯後的www資料夾,復制到遠程地址(目錄結構不要改變), 例如:建議使用app-framework 1.加入jquery mobile1.4点击打开链接 2.加入app-frame ...
- SQLSERVER编译与重编译
SQLSERVER编译与重编译 编译的含义 当SQLSERVER收到任何一个指令,包括查询(query).批处理(batch).存储过程.触发器(trigger) .预编译指令(prepared st ...
- 数据类型 -- uint32_t 类型
整型的每一种都有无符号(unsigned)和有符号(signed)两种类型(float和double总是带符号的),在默认情况下声明的整型变量都是有符号的类型(char有点特别),如果需声明无符号类型 ...
- 在MVC中加载view(点开链接)的方式
主要有: Html.ActionLink Html.RenderPartial Html.RenderAction Html.Partial AJAX.ActionLink load 浏览器对象模型 ...
- java 串口通信实现流程
1.下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java 2.下载下来的包解压后按照说明放到JAVA_HOME即JAVA的安装路径下面去 ...
- TFS看板的设计
列 产品开发的整个流程如下图,将流程配置到看板的列: 需求池-->就绪-->开发-->测试-->待验收 -->待发布 -->已关闭 一般将Bug和需求放在一块看版上 ...
- IOS 设置子控件的frame(layoutSubviews and awakeFromNib)
如果控件是通过xib或者storyboard创建出来的就会调用该方法 - (void)awakeFromNib :该方法只会调用一次 // 如果控件是通过xib或者storyboard创建出来的就 ...
- IOS 控制器View的创建方式(方式的优先级 、view的延迟加载)
MJViewController的view的创建 的方式的优先级 控制器view的延迟加载 ● 控制器的view是延迟加载的:用到时再加载 ● 可以用isViewLoaded方法判断一个UIViewC ...
- python实现栈的算法
以下来源“悟空”的讲课视频,我只是对内容加深以下理解,做一些说明: 栈作为一种数据结构,是一种只能在一端进行插入和删除操作.它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要 ...
- jQuery支持链式编程,一句话实现左侧table页+常用筛选器总结
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...