leetcode 37. Sudoku Solver
2017-05-23 02:04
459 查看
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.
Subscribe to see which companies asked this question.
判断是不是数独,这题还是有点难度的,想到的办法就是对没有填入数字的位置进行测试,目前合理则前进,不合理则回退,1-9都不行就返回FALSE
public class Solution {
public void solveSudoku(char[][] board) {
helper(board);
}
public boolean helper(char[][]board){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]=='.'){
for(char m='1';m<='9';m++){
if(isvalid(board,i,j,m)){
board[i][j]=m;
if(!helper(board))board[i][j]='.';
else return true;
}
}
return false;
}
}
}
return true;
}
public boolean isvalid(char[][]board,int i,int j,char c){
//row
for(int m=0;m<9;m++){
if(board[i][m]==c)return false;
}
//column
for(int n=0;n<9;n++){
if(board
[j]==c)return false;
}
//inner
for(int m=i/3*3;m<i/3*3+3;m++){
for(int n=j/3*3;n<j/3*3+3;n++){
if(board[m]
==c)return false;
}
}
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.
Subscribe to see which companies asked this question.
判断是不是数独,这题还是有点难度的,想到的办法就是对没有填入数字的位置进行测试,目前合理则前进,不合理则回退,1-9都不行就返回FALSE
public class Solution {
public void solveSudoku(char[][] board) {
helper(board);
}
public boolean helper(char[][]board){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]=='.'){
for(char m='1';m<='9';m++){
if(isvalid(board,i,j,m)){
board[i][j]=m;
if(!helper(board))board[i][j]='.';
else return true;
}
}
return false;
}
}
}
return true;
}
public boolean isvalid(char[][]board,int i,int j,char c){
//row
for(int m=0;m<9;m++){
if(board[i][m]==c)return false;
}
//column
for(int n=0;n<9;n++){
if(board
[j]==c)return false;
}
//inner
for(int m=i/3*3;m<i/3*3+3;m++){
for(int n=j/3*3;n<j/3*3+3;n++){
if(board[m]
==c)return false;
}
}
return true;
}
}
相关文章推荐
- 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
- Java [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
- LeetCode-37. Sudoku Solver (JAVA)(数独游戏解集)
- [Leetcode]_37 Sudoku Solver
- [leetcode 37] Sudoku Solver
- LeetCode 37 Sudoku Solver
- leetcode[37]Sudoku Solver
- LeetCode 37 - Sudoku Solver