您的位置:首页 > 其它

Sudoku Solver

2015-09-04 01:44 405 查看
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.

Solution:

class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
memset(row, true, sizeof(row));
memset(col, true, sizeof(col));
memset(block, true, sizeof(block));
for(int i = 0; i < 9; ++i)
for(int j = 0; j < 9; ++j)
{
if(board[i][j] != '.')
{
int k = board[i][j] - '0';
row[i][k] = false;
col[j][k] = false;
block[i/3*3+j/3][k] = false;
}
}

dfs(board, 0);
}

bool dfs(vector<vector<char> >&board, int index)
{
if(index > 80) return true;
int i = index / 9, j = index % 9;
if(board[i][j] != '.') return dfs(board, index + 1);
for(int k = 1; k <= 9; ++k)
{
if(row[i][k] && col[j][k] && block[i/3*3+j/3][k])
{
board[i][j] = k + '0';
row[i][k] = false;
col[j][k] = false;
block[i/3*3+j/3][k] = false;
if(dfs(board, index + 1)) return true;
row[i][k] = true;
col[j][k] = true;
block[i/3*3+j/3][k] = true;
}
}
board[i][j] = '.';

return false;
}

private:
bool row[9][10];
bool col[9][10];
bool block[9][10];
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: