LeetCode: solveSudoku 解题报告
2014-11-01 20:54
225 查看
[b]Sudoku Solver[/b]
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.
View Code
[b]GITHUB代码:[/b]
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/SolveSudoku.java
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.
public class Solution { public void solveSudoku(char[][] board) { // 3:01 if (board == null || board.length == 0 || board[0].length == 0) { return; } dfs(board, 0, 0); } public boolean dfs(char[][] board, int x, int y) { // 3:01 // next row. if (y >= 9) { return dfs(board, x + 1, 0); } if (x >= 9) { return true; } // skip the number. if (board[x][y] != '.') { return dfs(board, x, y + 1); } // solve the current node. // BUG2: c start from 1 not 0. for (char c = '1'; c <= '9'; c++) { board[x][y] = c; if (isValid(board, x, y, c) && dfs(board, x, y + 1)) { return true; } board[x][y] = '.'; } return false; } public boolean isValid(char[][] board, int x, int y, char c) { // the current row. for (int i = 0; i < 9; i++) { if (y != i && c == board[x][i]) { return false; } } // the current col. for (int i = 0; i < 9; i++) { // BUG1: should use board[i][y] if (x != i && c == board[i][y]) { return false; } } // the current block. int startX = x / 3 * 3; int startY = y / 3 * 3; for (int k = 0; k < 9; k++) { int indexX = startX + k / 3; int indexY = startY + k % 3; if (indexX == x && indexY == y) { continue; } if (board[indexX][indexY] == c) { return false; } } return true; } }
View Code
[b]GITHUB代码:[/b]
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/SolveSudoku.java
相关文章推荐
- [LeetCode 解题报告]001.Two Sum
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- [Leetcode] 64. Minimum Path Sum 解题报告
- 【LeetCode】Longest Consecutive Sequence 解题报告
- [Leetcode] 451. Sort Characters By Frequency 解题报告
- [Leetcode] 367. Valid Perfect Square 解题报告
- 【LeetCode】1. Two Sum 解题报告
- [leetcode] 297. Serialize and Deserialize Binary Tree 解题报告
- [Leetcode] 733. Flood Fill 解题报告
- [leetcode] 147. Insertion Sort List 解题报告
- Leetcode 415. Add Strings 字符串加法 解题报告
- [Leetcode] 599. Minimum Index Sum of Two Lists 解题报告
- [leetcode] 143. Reorder List 解题报告
- LeetCode 120. Triangle 解题报告
- [leetcode] 25. Reverse Nodes in k-Group 解题报告
- [leetcode] 87. Scramble String 解题报告
- leetcode解题报告:56. Merge Intervals
- [Leetcode] 67. Add Binary 解题报告
- LeetCode: Subsets 解题报告
- 【LeetCode】Longest Substring Without Repeating Characters 解题报告