37. Sudoku Solver
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.
深度优先遍历解决问题,从(0,0)点开始遍历,每个点依次试1-9的数,合法或者已经有数则递归到下个位置,直到到达(9,0)点,说明所有点都解决了
public class Solution { public void solveSudoku(char[][] board) { solveSudoku_helper(board,0,0); } public boolean vaild(char[][] board, int x,int y,char val) { for (int i=0;i<9;i++){ if (board[i][y]==val){ return false; } if (board[x][i]==val){ return false; } } for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ if (board[x/3*3+i][y/3*3+j]==val) return false; } } return true; } public boolean solveSudoku_helper(char[][] board,int x,int y) { if (x==9&&y==0) return true; if (board[x][y]=='.'){ for (int i=1;i<=9;i++){ if (vaild(board,x,y,(char)(i+'0'))){ board[x][y]=(char)(i+'0'); if(solveSudoku_helper(board,x+(y+1)/9,(y+1)%9)==true) return true; board[x][y]='.'; } } }else { if(solveSudoku_helper(board,x+(y+1)/9,(y+1)%9)==true) return true; } return false; } }