编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。
空白格用 '.'
表示。
一个数独。
答案被标成红色。
Note:
- 给定的数独序列只包含数字
1-9
和字符'.'
。 - 你可以假设给定的数独只有唯一解。
- 给定数独永远是
9x9
形式的。
本人还是太菜了,用的方法貌似效率不太高。
class Solution {
public:
bool isValidPositionSudoku(vector<vector<char>>& board, int height,int width)
{
//judge line
for(int j=0;j<9;j++)
{
if(j != width && board[height][j] == board[height][width]) return false;
if(j != height && board[j][width] == board[height][width]) return false;
}
//judge block
int x=height/3;
int y=width/3;
for(int j=3*x;j<3*x+3;j++)
for(int k=3*y;k<3*y+3;k++)
{
if(j == height && k == width) continue;
if(board[j][k] == board[height][width]) return false;
}
//return
return true;
}
void solveSudoku(vector<vector<char>>& board)
{
vector<vector<char>> initboard = board;
int pos = 0;
while (pos>=0 && pos<81)
{
//find next pos of '.'
while (pos<81 && initboard[pos/9][pos%9] != '.')
{
++pos;
}
if(pos == 81) break;
//init value
if(board[pos/9][pos%9] == '.') board[pos/9][pos%9] = '0';
if(board[pos/9][pos%9] == '0') board[pos/9][pos%9]++;
//find first valid value or over board
while(board[pos/9][pos%9]<='9' && !isValidPositionSudoku(board,pos/9,pos%9))
{
board[pos/9][pos%9]++;
}
//if over board,then jump back;
if (board[pos/9][pos%9] > '9')
{
//jump back, maybe move many steps
do
{
//recover value
board[pos/9][pos%9] = '0';
//jump to last pos of '.'
do
{
--pos;
}while(pos>=0 && initboard[pos/9][pos%9] != '.');
//judge pos if it is valid
if(pos<0) break;
//last pos's value add 1
board[pos/9][pos%9]++;
}while(board[pos/9][pos%9]>'9');
}
//if valid,jump to next pos
else
{
++pos;
}
}
}
};