您的位置:首页 > 其它

leetCode Sudoku Solver

2014-12-14 22:44 246 查看
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 avalid(vector<vector<char> > &board,int count, int num)
{
char chr = '0' + num;
int row = count / 9;
int col = count % 9;
int b_r = row / 3 * 3;
int b_c = col / 3 * 3;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
{
if(board[b_r + i][b_c + j] == chr)return false;
}

for(int i = 0; i < 9; i++)
if(board[row][i] == chr)return false;
for(int i = 0; i < 9; i++)
if(board[i][col] == chr)return false;

return true;

}

bool solve(vector<vector<char> > &board, int count)
{
if(count == 81)return true;

int row = count / 9;
int col = count % 9;
int b_r = row / 3 * 3;
int b_c = col / 3 * 3;

if(board[row][col] != '.')return solve(board, count + 1);

for(int i = 1; i <= 9; i++)
{
if(avalid(board, count, i))
{
board[row][col] = '0' + i;
if(solve(board, count))return true;
board[row][col] = '.';
}
}

return false;

}

void solveSudoku(vector<vector<char> > &board)
{
solve(board, 0);
}

};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: