1. 程式人生 > >排列組合和回溯演算法-面試題

排列組合和回溯演算法-面試題

    public void solveSudoku(char[][] board) {
        ArrayList<ArrayList<Integer>> emptyLocations=
        		new ArrayList<ArrayList<Integer>>();
        for(int row=0;row<9;row++){
        	for(int col=0;col<9;col++){
        		if(board[row][col]=='.'){
        			ArrayList<Integer> location=new ArrayList<Integer>();
        			location.add(row);location.add(col);
        			emptyLocations.add(location);
        		}
        	}
        }
        solve(board,0,emptyLocations);
    }
    private boolean solve(char[][] board,int index,ArrayList<ArrayList<Integer>> emptyLocations){
    	if(index==emptyLocations.size()){
    		return true;
    	}
    	ArrayList<Integer> location=emptyLocations.get(index);
    	int row=location.get(0),col=location.get(1);
    	for(char c='1';c<='9';c++){ 
    		if(isValid(board,row,col,c)){
    			board[row][col]=c;
    			if(solve(board,index+1,emptyLocations)){
    				return true;
    			}else{
    				board[row][col]='.';
    			}
    		}
    	}
    	return false;
    }
    public boolean isValid(char[][] board,int row,int col,char c){
    	//驗證行
    	for(int i=0;i<9;i++){
    		if(board[row][i]==c)
    			return false;
    	}
    	//驗證列
    	for(int i=0;i<9;i++){
    		if(board[i][col]==c)
    			return false;
    	}
    	//驗證3*3格子
    	for(int i=(row/3)*3;i<(row/3)*3+3;i++){
    		for(int j=(col/3)*3;j<(col/3)*3+3;j++){
    			if(board[i][j]==c)
    				return false;
    		}
    	}
    	return true;
    }