[Leetcode] 37. Sudoku Solver
2015-03-15 06:47
423 查看
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.
solve里,第一个return true代表能够完成填表,第二个return false代表这个格子试过了1 - 9所有数字都没有return true过,代表都不行,所以return false;第三个return true所有格子都遍历完了,说明填完了,所以return true。
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.
solve里,第一个return true代表能够完成填表,第二个return false代表这个格子试过了1 - 9所有数字都没有return true过,代表都不行,所以return false;第三个return true所有格子都遍历完了,说明填完了,所以return true。
public class Solution { public void solveSudoku(char[][] board) { solve(board); } private boolean solve(char[][] board){ for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ if(board[i][j] == '.'){ 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; } private boolean isValid(char[][] board, int i, int j){ for(int k = 0; k < 9; k++){ if(k != j && board[i][k] == board[i][j]) return false; } for(int k = 0; k < 9; k++){ if(k != i && board[k][j] == board[i][j]) return false; } for(int row = i / 3 * 3; row < i / 3 * 3 + 3; row++){ for(int col= j / 3 * 3; col < j / 3 * 3 + 3; col++){ if((row != i || col != j) && board[row][col]==board[i][j]) return false; } } return true; } }
相关文章推荐
- leetcode 37 Sudoku Solver
- leetcode 37. Sudoku Solver
- leetcode 37 Sudoku Solver
- leetcode: 37. Sudoku Solver
- LeetCode 37 Sudoku Solver(求解数独)
- LeetCode 37. Sudoku Solver(数独Ⅱ)
- LeetCode-----37. Sudoku Solver(解数读)
- leetcode 37: Sudoku Solver
- leetcode 37. Sudoku Solver
- leetcode 37 sudoku solver
- python实现 LeetCode37——Sudoku Solver
- LeetCode 37 Sudoku Solver(求解数独)(*)
- LeetCode 37 Sudoku Solver (C,C++,Java,Python)
- [LeetCode 36&37] Valid Sudoku & Sudoku Solver (数独问题)
- leetcode-37-sudoku solver
- [LeetCode 37] Sudoku Solver回溯解法
- LeetCode_37 Sudoku Solver
- leetcode 37. Sudoku Solver
- LeetCode 37 Sudoku Solver 回溯和深度遍历 还要学习
- leetcode 37:Sudoku Solver