LeetCode-----37. Sudoku Solver(解数读)
2016-09-29 15:26
549 查看
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.
回溯法:尝试所有的解,不合适的话返回再试。(八皇后问题)
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.
回溯法:尝试所有的解,不合适的话返回再试。(八皇后问题)
public class Solution { public void solveSudoku(char[][] board){ solve(board); } public boolean solve(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 (isValid(board, i, j) && solve(board)){ return true; } board[i][j] = '.'; } return false; } } return true; } public boolean isValid(char[][] board, int a, int b){ Set<Character> contained = new HashSet<Character>(); for(int j=0;j<9;j++){ if(contained.contains(board[a][j])) return false; if(board[a][j]>'0' && board[a][j]<='9') contained.add(board[a][j]); } contained = new HashSet<Character>(); for(int j=0;j<9;j++){ if (contained.contains(board[j][b])) { return false; } if (board[j][b]>'0' && board[j][b]<='9') { contained.add(board[j][b]); } } contained = new HashSet<Character>(); for (int m = 0; m < 3; m++) { for (int n = 0; n < 3; n++){ int x = a / 3 * 3 + m, y = b / 3 * 3 + n; if (contained.contains(board[x][y])) { return false; } if (board[x][y] > '0' && board[x][y] <= '9') { contained.add(board[x][y]); } } } return true; } }
相关文章推荐
- LeetCode 37 Sudoku Solver 回溯和深度遍历 还要学习
- [leetcode] 37. Sudoku Solver
- Leetcode 37. Sudoku Solver
- [LeetCode]37. Sudoku Solver
- LeetCode-37-Sudoku Solver, list转字符串join,回溯
- LeetCode(37) Sudoku Solver
- leetcode习题解答:37. Sudoku Solver
- LeetCode 37: Sudoku Solver
- LeetCode 37. Sudoku Solver(数读游戏)
- Leetcode37 Sudoku Solver
- LeetCode 37.Sudoku Solver
- Java [leetcode 37]Sudoku Solver
- [leetcode 37]sudoku solver
- [leetcode 37] Sudoku Solver
- Leetcode||37. Sudoku Solver
- LeetCode37 Sudoku Solver
- leetcode 37. Sudoku Solver
- Leetcode-37: Sudoku Solver
- leetcode[37]Sudoku Solver
- leetcode-37 Sudoku Solver