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


LL's solution: --DFS

public class Solution { 
    public boolean isValid(int value,int row,int col,char[][] board){
        boolean res = true;
        for(int i=0;i<9;i++){
            //check row
            if(Character.getNumericValue(board[row][i])==value){
                res = false;
                break;
            }
            //check col
            if(Character.getNumericValue(board[i][col])==value){
                res = false;
                break;
            }
            //check square
            int row_s = 3*(int)(row/3) + (int)(i/3);
            int col_s = 3*(int)(col/3) + i%3;
            if(Character.getNumericValue(board[row_s][col_s])==value){
                res = false;
                break;
            }
        }
        return res;       
    }
    
    public boolean DFS(ArrayList<int[]> empty,char[][] board,int i,int len){
        int[] index = empty.get(i);
        int row = index[0];
        int col = index[1];
        boolean res=false;
        for(int v = 1;v<=9;v++){
            if(isValid(v,row,col,board)){
                //System.out.print("("+row+","+col+")->"+v+"|");
                board[row][col] = (char) (v+'0');
                if(i<len-1){
                    res = DFS(empty,board,i+1,len);
                    if(res)
                        break;   
                    else
                    	board[row][col] = '.';
                }
                else{	// the last one
                    res = true;
                    break;
                }
            } 
        }
        return res;
        
    }
    
    public void solveSudoku(char[][] board) {
        // Start typing your Java solution below
        // DO NOT write main() function
        //scan board for empty spot
        ArrayList<int[]> empty = new ArrayList<int[]>();
        for(int row = 0;row<9;row++)
            for(int col = 0;col<9;col++)
                if(board[row][col]=='.'){
                	int [] tmp = {row,col};
                    empty.add(tmp);
                    }
        
        int len = empty.size();
        DFS(empty,board,0,len);
        
        return;
        
    }
}

Note:

1.对于square的index转换要特别小心

2.对于终止recurtion的判断条件,i<len还是i<len-1需小心

3.board里面存的是char,等值判断用的是int,来回转换要注意

char -> int: Charaster.getNumericValue(c)

int -> char: (char)(i+'0')

4.DFS返回false的时候要抹除已经填写的board[row][col]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值