【leetcode】Sudoku Solver

时间:2021-06-17 19:31:02

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.

【leetcode】Sudoku Solver

【leetcode】Sudoku Solver

A sudoku puzzle...

【leetcode】Sudoku Solver

【leetcode】Sudoku Solver

...and its solution numbers marked in red.

采用回溯法,利用递归实现
如果当前的元素满足数独条件,则继续判断下一个元素。
如果当前的元素不满足数独条件,则返回,递归回溯到上一个元素继续查找
 
由于肯定有解,所以在判断的时候可以不必使用hash表,直接判断其他位置的元素与当前要判断的元素是否相等就可以了。
 
 
 class Solution {
public: bool isValid(vector<vector<char> > &board,int i0,int j0)
{
char target=board[i0][j0]; for(int i=;i<;i++)
{
if(i==i0) continue;
if(board[i][j0]==target)
{
return false;
}
} for(int j=;j<;j++)
{
if(j==j0) continue;
if(board[i0][j]==target)
{
return false;
}
} for(int i=i0/*;i<i0/*+;i++)
{ for(int j=j0/*;j<j0/*+;j++)
{
if(i==i0&&j==j0) continue;
if(board[i][j]==target)
{
return false;
}
}
} return true;
} bool scanPos(vector<vector<char> > &board,int pos)
{
if(pos==) return true; bool flag=false;
int i0=pos/;
int j0=pos%; if(board[i0][j0]!='.')
{
return scanPos(board,pos+);
} for(int j=;j<=;j++)
{ board[i0][j0]=''+j;
if(isValid(board,i0,j0))
{
if(scanPos(board,pos+))
{
flag=true;
break;
}
}
} if(flag==false)
{
board[i0][j0]='.';
return false;
}
else
{
return true;
}
} void solveSudoku(vector<vector<char> > &board) {
scanPos(board,);
}
};