您的位置:首页 > 其它

【leetcode刷题笔记】Sudoku Solver

2014-07-25 12:07 260 查看
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.

题解:递归。在每个空位上尝试放置0~9的数,然后递归的解决剩下的空位。

单独写一个判断board目前(x,y)处的数是否合法的函数 public boolean isValidSudoku(char[][] board,int x,int y) ,它就只用检查跟(x,y)同行,同列和同一个九宫格的元素是否和board[x][y]有重复即可。(其实在九宫格中只用判断4个和(x,y)不同行列的元素,因为和(x,y)同行列的我们已经判断过了)。

代码如下:

public class Solution {
public boolean isValidSudoku(char[][] board,int x,int y) {
//check for row x
for(int i = 0;i < 9;i++)
if(i!=y && board[x][i] == board[x][y])
return false;

//check for column y
for(int i = 0;i < 9;i++)
if(i!= x &&board[i][y] == board[x][y])
return false;

//check for the 3*3 square (x,y) belongs to
for(int i = 3 * (x/3);i<3*(x/3)+3;i++){
for(int j = 3*(y/3);j<3*(y/3)+3;j++){
if(i!=x && j != y && board[i][j] == board[x][y] )
return false;
}
}

return true;
}

private boolean solveSudokuRecur(char[][] board){
for(int i = 0;i < 9;i++){
for(int j = 0;j < 9;j++){
if(board[i][j] != '.')
continue;
for(int k = 1;k <= 9;k++){
board[i][j] = (char)(k + '0');
if(isValidSudoku(board,i,j) && solveSudokuRecur(board))
return true;
board[i][j] = '.';
}
return false;
}
}
return true;
}
public void solveSudoku(char[][] board) {
solveSudokuRecur(board);
}
}


注意之前做过的Valid Sudoku这道题是判断整个数独是否合法,而不是单独某个位置(x,y)是否合法,它需要遍历整个数独,所以这段代码不能拿来用了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: