您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Sudoku Solver

2012-10-19 00:07 519 查看
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.

public static void SudokuSolver(List<List<char>> board)
{
solver(board);
}

public static bool solver(List<List<char>> board)
{
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 9; c++)
{
if (board[r][c] == '.')
{
for (int k = 1; k <= 9; k++)
{
board[r][c] = Convert.ToChar('0' + k);
if (isValid(board, r, c))
{
if(solver(board))
return true;
}
board[r][c] = '.';
}
return false;
}
}
}
return true;
}

public static bool isValid(List<List<char>> board, int r, int c)
{
//////////////CHECK ROW/////////////////////
bool[] Row = new bool[9];
for (int i = 0; i < 9; i++)
{
if (board[r][i] >= '1' && board[r][i] <= '9')
{
if (Row[board[r][i] - '1'] == false)
Row[board[r][i] - '1'] = true;
else
return false;
}
}

/////////////CHECK COLUMN//////////////////
bool[] Col = new bool[9];
for (int i = 0; i < 9; i++)
{
if (board[i][c] >= '1' && board[i][c] <= '9')
{
if (Col[board[i][c] - '1'] == false)
Col[board[i][c] - '1'] = true;
else
return false;
}
}

/////////////CHECK GRID///////////////////
bool[] Grid = new bool[9];
// r / 3 * 3 = beginning row number of that grid
// c / 3 * 3 = beginning column number of that grid
for (int i = (r / 3) * 3; i < (r / 3) * 3 + 3; i++)
{
for (int j = (c / 3) * 3; j < (c / 3) * 3 + 3; j++)
{
if (board[i][j] >= '1' && board[i][j] <= '9')
{
if (Grid[board[i][j] - '1'] == false)
Grid[board[i][j] - '1'] = true;
else
return false;
}
}
}

return true;
}


代码分析:

  递归,就是每个数字试,检查行列格子都Valid就递归到下一个,如果不Valid记得要把当前数字归空( '.' ),因为这这个格子有可能0~9都不Valid,需要回溯到前一个格子。DP有点不知道怎么弄。

  我也有个Follow Up, 如果要打印所有可能的解。该怎么写呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: