您的位置:首页 > 其它

LeetCode: Sudoku Solver

2015-01-17 09:41 351 查看
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 {
private:
int col[9][9];
int row[9][9];
int square[9][9];
public:
void solveSudoku(vector<vector<char> > &board) {
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(board[i][j] != '.')
{
row[i][board[i][j] - '1'] = 1;
col[j][board[i][j] - '1'] = 1;
square[i/3*3 + j/3][board[i][j] - '1'] = 1;
}
}
solve(0, board);
}
bool solve(int index, vector<vector<char> > &board)
{
if(index == 81)
return true;
int x = index/9, y = index%9;
if(board[x][y] != '.')
solve(index+1, board);
else
{
for(int i = 0; i < 9; i++)
{
if(isValid(x, y, i, board))
{
fill(x, y, i, board);
if(solve(index+1, board))
{
return true;
}
revert(x, y, i, board);
}

}
return false;

}
}
bool isValid(int x, int y, int value, vector<vector<char> > &board)
{
if(row[x][value] == 1 || col[y][value] == 1 || square[x/3*3 + y/3][value] == 1)
return false;
else
return true;
}
void fill(int x, int y, int value, vector<vector<char> > &board)
{
board[x][y] = value + '1';
row[x][value] = 1;
col[y][value] = 1;
square[x/3*3 + y/3][value] = 1;
}
void revert(int x, int y, int value, vector<vector<char> > &board)
{
board[x][y] = '.';
row[x][value] = 0;
col[y][value] = 0;
square[x/3*3 + y/3][value] = 0;
}
};

Round 2:

class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
int row[9][9] = {0};
int col[9][9] = {0};
int zone[9][9] = {0};
for(int i = 0; i < board.size(); i++)
for(int j = 0; j < board[0].size(); j++)
{
if(board[i][j] != '.')
{
row[i][board[i][j] - '1'] = 1;
col[j][board[i][j] - '1'] = 1;
zone[(i/3)*3+j/3][board[i][j] - '1'] = 1;
}
}
bool flag = false;
dfs(board, row, col, zone, 0, flag);

}
private:
void dfs(vector<vector<char> > &board, int row[][9], int col[][9], int zone[][9], int index, bool &flag)
{
if(index == 81)
{
flag = true;
return;
}
int i = index / 9;
int j = index % 9;
char cur = board[i][j];
int num = cur - '0';
if(cur == '.')
{
for(int k = 0; k < 9; k++)
{
if(row[i][k] != 0 || col[j][k] != 0 || zone[(i/3)*3+j/3][k] != 0)
continue;
row[i][k] = 1;
col[j][k] = 1;
zone[(i/3)*3+j/3][k] = 1;
board[i][j] = k + '1';
dfs(board, row, col, zone, index+1, flag);
if(flag)
return;
row[i][k] = 0;
col[j][k] = 0;
zone[(i/3)*3+j/3][k] = 0;
board[i][j] = '.';
}
}
else
dfs(board, row, col, zone, index+1, flag);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: