Leetcode dfs Sudoku Solver
2014-09-07 13:05
363 查看
Sudoku Solver
Total Accepted: 11799 TotalSubmissions: 56732My Submissions
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.
题意:填充数独,返回是否填充成功
思路:dfs
找一个还没填充的位置,尝试填写0-9其中的一个数字,判断是否理。
如果合理,则可以转移到一个同样子问题,所以可以采用递归的方式实现。
bool solveSudoku(vector<vector<char> >&board)
返回是否成功填充当前状态为 board的数独
bool isValid(const vector<vector<char> >&board, int x, int y){
//检查行
for(int j = 0; j < 9; ++j) if(j != y && board[x][j] == board[x][y]) return false;
//检查列
for(int i = 0; i < 9; ++i) if(i != x && board[i][y] == board[x][y]) return false;
//检查小方块
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j){
if(!(x/3 * 3 + i == x && y /3 * 3 + j == y) && board[x/3 * 3 + i][y /3 * 3 + j] == board[x][y]) return false;
}
return true;
}
bool solveSudoku(vector<vector<char> >&board)
{
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] == '.'){
for(int k = 0; k < 9; ++k){
board[i][j] = k + '1' ;
if(isValid(board, i, j) && solveSudoku(board)) return true;
board[i][j] = '.';
}
return false;
}
}
}
return true; //漏写了这句,WA了好多次
}
相关文章推荐
- leetcode Sudoku Solver python
- leetcode Sudoku Solver
- 37. Sudoku Solver leetcode python new season 2016
- leetcode 37. Sudoku Solver 一个经典的DFS深度优先搜索的做法
- [leetcode]Sudoku Solver
- [LeetCode]37 Sudoku Solver
- LeetCode-难题集之Sudoku_Solver
- LeetCode Sudoku Solver
- LeetCode : Sudoku Solver [java]
- leetcode:Valid Sudoku and Sudoku Solver
- LeetCode 37. Sudoku Solver|DFS算法
- LeetCode Sudoku Solver
- LeetCode Sudoku Solver
- LeetCode---Sudoku Solver
- LeetCode--sudoku-solver
- LeetCode: Sudoku Solver [036]
- Sudoku Solver leetcode java
- LeetCode Sudoku Solver
- LeetCode Sudoku Solver
- LeetCode37 - Sudoku Solver