N-Queens

public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> res = new ArrayList<String[]>();
        dfs(n,0,new int[n],res);
        return res;
    }
    public void dfs(int n,int row,int[]QueenList,ArrayList<String[]> res){
        if(row==n){
            String[] output= new String[n];
            for(int i=0;i<n;i++){
                StringBuilder sb = new StringBuilder();
                for(int j=0;j<n;j++){
                    if(j==QueenList[i]){
                        sb.append('Q');
                    }else{
                        sb.append('.');
                    }
                }
                output[i] = sb.toString();
            }
            res.add(output);
        }
        for(int col=0;col<n;col++){
            if(isSafe(n,row,col,QueenList)){
                QueenList[row] = col;
                dfs(n,row+1,QueenList,res);
            }
        }
    }
    public boolean isSafe(int n,int row,int col,int QueenList[]){
        for(int preRow=0;preRow<row;preRow++){
            int preCol = QueenList[preRow];
            if(preCol==col){
                return false;
            }else if(Math.abs(preCol-col)==row-preRow){
                return false;
            }
        }
        return true;
    }
}

 

posted @ 2014-02-06 14:19  krunning  阅读(139)  评论(0编辑  收藏  举报