leetcode 93: Sudoku Solver (uncompleted.)

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.

uncompleted.


public class Solution {
        ArrayList<HashSet<Character>> line; 
        ArrayList<HashSet<Character>> col; 
        ArrayList<HashSet<Character>> square;
        int sz;
    
    public void solveSudoku(char[][] board) {
        // Start typing your Java solution below
        // DO NOT write main() function
        sz = board.length;
        
        ArrayList<HashSet<Character>> line = new ArrayList<HashSet<Character>>(); 
        ArrayList<HashSet<Character>> col = new ArrayList<HashSet<Character>>(); 
        ArrayList<HashSet<Character>> square = new ArrayList<HashSet<Character>>();
        
        for(int i=0; i<9; i++) {
            line.add( new HashSet<Character>());
            col.add( new HashSet<Character>());
            square.add( new HashSet<Character>());
        }
        
        int count=0;
        for(int i=0; i<sz; i++) {
            for(int j=0; j<sz; j++) {
                if(board[i][j] != '.') {
                    ++count;
                    line.get(i).add( board[i][j] );
                    col.get(i).add( board[i][j] );
                    square.get((i/3)*3+j%3).add( board[i][j]);
                }    
            }
        }
        
        sudokuRec(board, 0);
    }
    
    private void sudokuRec(char[][] board, int level){
        if(level== sz*sz) {
            return;
        }   
        
        for(int l=level; l<sz*sz;l++) {
            int i=level/sz;
            int j=level%sz;
                if(board[i][j]=='.') {
                    for(char k='1';k<='9';k++){
                        if(!line.get(i).contains(k) && !col.get(j).contains(k) && !square.get((i/3)*3+j%3).contains(k) ){
                            board[i][j]=k;
                            line.get(i).add(k);
                            col.get(j).add(k);
                            square.get((i/3)*3+j/3).add(k);
                            sudokuRec(board,l+1);
                            line.get(i).remove(k);
                            col.get(j).remove(k);
                            square.get((i/3)*3+j/3).remove(k);
                            board[i][j]='.';
                        }
                    }
                } 
        }
    }
}















posted @ 2013-03-01 00:59  西施豆腐渣  阅读(140)  评论(0编辑  收藏  举报