[leetcode]37. Sudoku Solver
阿新 • • 發佈:2018-12-03
回溯法一定要記得恢復原值,因為前後值都有關聯
有一種牛逼八皇后不用這樣
if(solve(board))
return true; //If it's the solution return true
else
board[i][j] = '.'; //Otherwise go back
}
是因為它另拿了一個數組存結果,沒有利用原來的棋盤
public class Solution { public void solveSudoku(char[][] board) { if(board == null || board.length == 0) return; solve(board); } public boolean solve(char[][] board){ for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[0].length; j++){ if(board[i][j] == '.'){ for(char c = '1'; c <= '9'; c++){//trial. Try 1 through 9 if(isValid(board, i, j, c)){ board[i][j] = c; //Put c for this cell if(solve(board)) return true; //If it's the solution return true else board[i][j] = '.'; //Otherwise go back } } return false; } } } return true; } private boolean isValid(char[][] board, int row, int col, char c){ for(int i = 0; i < 9; i++) { if(board[i][col] != '.' && board[i][col] == c) return false; //check row if(board[row][i] != '.' && board[row][i] == c) return false; //check column if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' && board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block } return true; } }
class Solution { public void solveSudoku(char[][] board) { boolean res=backtrack(board); } private boolean backtrack(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+48); if(isValidSudoku(board)){ if(backtrack(board)) return true; board[i][j]='.'; } else{ board[i][j]='.'; } } return false; } } } return true; } public boolean isValidSudoku(char[][] board) { for(int i=0;i<9;i+=3){ for(int j=0;j<9;j+=3){ if(!CheckSquare(board,i,j)){ return false; } } } for(int i=0;i<9;i++){ if(!CheckRow(board,i)){ return false; } } for(int j=0;j<9;j++){ if(!CheckColumn(board,j)){ return false; } } return true; } private boolean CheckRow(char[][] board,int i){ Set<Character> set=new HashSet<>(); for(int j=0;j<9;j++){ if(board[i][j]!='.'){ if(!set.contains(board[i][j])){ set.add(board[i][j]); } else{ return false; } } } return true; } private boolean CheckColumn(char[][] board,int j){ Set<Character> set=new HashSet<>(); for(int i=0;i<9;i++){ if(board[i][j]!='.'){ if(!set.contains(board[i][j])){ set.add(board[i][j]); } else{ return false; } } } return true; } private boolean CheckSquare(char[][] board,int i,int j){ Set<Character> set=new HashSet<>(); int p=i,q=j; for(p=i;p<i+3;p++){ for(q=j;q<j+3;q++){ if(board[p][q]!='.'){ if(!set.contains(board[p][q])){ set.add(board[p][q]); } else{ return false; } } } } return true; } }