LeetCode 第 37 题 (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.
这个题目说实话用来作为面试题不太适合。除非以前做个,否则很少有人能在很短时间内做完。
下面是我写的一个解答。尽量写的比较易懂,没有追求运行速度。简单的来说这个算法就是试填 + 递归。
class Solution
{
public:
/**
* @brief 找到第一个需要填数字的位置
* @para pos 通过 pos 返回位置坐标, pos[0] 为行号, pos[1] 为列号
*/
bool findFirstEmptyPos(vector<vector<char>>& board, int pos[2])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (board[i][j] == '.')
{
pos[0] = i;
pos[1] = j;
return true;
};
}
}
return false;
}
/**
* @brief 判断一个数是否已经在这一3*3的小方块中出现过了
*/
bool containInBlock(vector<vector<char>>& board, int element, int row, int col)
{
int i = row / 3;
int j = col / 3;
for (int ii = 0; ii < 9 / 3; ii++)
{
for(int jj = 0; jj < 9 / 3; jj++)
{
if (board[i * 3 + ii][j * 3 + jj] == element) return true;
}
}
return false;
}
/**
* @brief 判断一个数是否已经在这一列出现过了
*/
bool containInCol(vector<vector<char>>& board, int element, int col)
{
for (int i = 0; i < 9; i++)
{
if (board[i][col] == element) return true;
}
return false;
}
/**
* @brief 判断一个数是否已经在这一行出现过了
*/
bool containInRow(vector<vector<char>>& board, int element, int row)
{
for (int i = 0; i < 9; i++)
{
if (board[row][i] == element) return true;
}
return false;
}
bool sudoku(vector<vector<char>>& board)
{
bool isOk;
int pos[2];
isOk = findFirstEmptyPos(board, pos); // 找到第一个需要填的位置
if(isOk == false) return true; // 如果都填满了,返回 true. 表示成功的找到解了
for(int j = '1'; j <= '9'; j ++)
{
if( containInRow(board, j, pos[0]) ) continue;
if( containInCol(board, j, pos[1]) ) continue;
if( containInBlock(board, j, pos[0], pos[1]) ) continue;
board[ pos[0] ][ pos[1] ] = j; // j 是一个可以填的值,试填之
isOk = sudoku( board );
if(isOk == true)
{
// 到这里了说明 j 填对了,并且后面的数也都填好了
return true;
}
board[ pos[0] ][ pos[1] ] = '.'; // 到这里说明 j 填的不对,恢复 board,重新填
}
return false; // 到这里了说明 1-9都试了全都不对,表明当前状态无解
}
void solveSudoku(vector<vector<char>>& board)
{
sudoku(board);
}
};