您的位置:首页 > 其它

[leetcode] 37. Sudoku Solver 解题报告

2015-12-21 16:22 357 查看
题目链接:https://leetcode.com/problems/sudoku-solver/

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:
bool DFS(vector<vector<char>>& board, int y, int x)
{
if(y == 9) return true;
if(x == 9) return DFS(board, y+1, 0);
if(board[y][x] != '.') return DFS(board, y, x+1);
for(int i = 1, a, b; i <= 9; i++)
{
for(a=0; a<9; a++) if(board[y][a]=='0'+i) break;
if(a != 9) continue;
for(a=0; a<9; a++) if(board[a][x]=='0'+i) break;
if(a != 9) continue;
for(a = y/3*3; a < y/3*3+3; a++)
{
for(b = x/3*3; b < x/3*3+3; b++)
if(board[a][b] == '0'+i) break;
if(b!=x/3*3+3) break;
}
if(!(a == y/3*3+3 && b==x/3*3+3)) continue;
board[y][x] = '0' + i;
if(DFS(board, y, x+1)) return true;
board[y][x] = '.';
}
return false;
}

void solveSudoku(vector<vector<char>>& board) {
DFS(board, 0, 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode DFS backtracking