【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)同行列的我们已经判断过了)。
代码如下:
注意之前做过的Valid Sudoku这道题是判断整个数独是否合法,而不是单独某个位置(x,y)是否合法,它需要遍历整个数独,所以这段代码不能拿来用了。
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)是否合法,它需要遍历整个数独,所以这段代码不能拿来用了。
相关文章推荐
- LeetCode解题笔记37 Sudoku Solver
- Leetcode 笔记 36 - Sudoku Solver
- leetcode笔记:Sudoku Solver
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
- LeetCode 笔记系列一 Median of Two Sorted Arrays
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
- LeetCode 笔记系列四 Remove Nth Node From End of List
- Leetcode Sudoku Solver
- [Leetcode] Sudoku Solver
- LeetCode 笔记系列 14 N-Queen II [思考的深度问题]
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
- LeetCode Online Judge 题目C# 练习 - Sudoku Solver
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
- LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]
- LeetCode 笔记系列七 Substring with Concatenation of All Words
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- [leetcode] sudoku solver:暴力还是优化
- LeetCode 笔记系列九 Search in Rotated Sorted Array
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]