leetcode--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.

public class Solution {
    boolean rowValid[][]=new boolean[9][10];//rowValid[i][j]表示第i行数字j是否已经使用
    boolean columnValid[][]=new boolean[9][10];//columnValid[i][j]表示第i列数字j是否已经使用
    boolean subBoardValid[][]=new boolean[9][10];//subBoardValid[i][j]表示第i个小格子内数字j是否已经使用
    public void solveSudoku(char[][] board) {
    	for(int i = 0; i < 9; i++)
    	      for(int j = 0; j < 9; j++)
    	        if(board[i][j] != '.')
    	          fill(i, j, board[i][j] - '0');
    	solve(board, 0);
    }
    
    boolean solve(char[][] board, int index){
    	if(index > 80)return true;// 0 <= index <= 80,index表示接下来要填充第index个格子
        int row = index / 9, col = index - 9*row;
        if(board[row][col] != '.')
          return solve(board, index+1);
        for(int val = '1'; val <= '9'; val++){//每个为填充的格子有9种可能的填充数字        
          if(isValid(row, col, val-'0')){
            board[row][col] = (char) val;
            fill(row, col, val-'0');
            if(solve(board, index+1))return true;
            clear(row, col, val-'0');
          }
        }
        board[row][col] = '.';//注意别忘了恢复board状态
        return false;
    }
    
    //判断在第row行col列填充数字val后,是否是合法的状态
    boolean isValid(int row, int col, int val){
      if(!rowValid[row][val] &&
         !columnValid[col][val] &&
         !subBoardValid[row/3*3+col/3][val])
         return true;
      return false;
    }
    
    //更新填充状态
    void fill(int row, int col, int val){
      rowValid[row][val] = true;
      columnValid[col][val] = true;
      subBoardValid[row/3*3+col/3][val] = true;
    }
    
    //清除填充状态
    void clear(int row, int col, int val){
      rowValid[row][val] = false;
      columnValid[col][val] = false;
      subBoardValid[row/3*3+col/3][val] = false;
    }
}


你可能感兴趣的:(leetcode--Sudoku Solver)