N皇后问题

class Solution {
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
ArrayList<ArrayList> solveNQueens(int n) {
// write your code here
ArrayList path = new ArrayList();
ArrayList<ArrayList> result = new ArrayList<ArrayList>();
if( n<0 )
return result;
int cols[] = new int[n];
DFS_helper(n,result,0,cols);
return result;

}
public void DFS_helper(int nQueens,ArrayList<ArrayList<String>> result,int row,int[] cols){
    if(row == nQueens ){
        ArrayList<String> path = new ArrayList<String>();
        for(int i = 0;i<nQueens ;i++){
            String s = "";
            for(int j = 0;j< nQueens ;j++){
                if(j == cols[i])
                    s = s + "Q";
                else
                    s = s + ".";
            }
            path.add(s);

        }
        result.add(path);
    }else{
        for(int i = 0;i<nQueens ;i++){
            cols[row] = i;
            if(isValid(row,cols))
                DFS_helper(nQueens,result,row + 1 ,cols);
        }
    }
}
public boolean isValid(int row ,int[] cols){
    for(int i=0;i<row;i++){
        if(cols[row] == cols[i] || Math.abs(cols[row] - cols[i]) == row - i)
        return false;
    }
    return true;
}

};

posted @ 2017-08-22 02:19  逸文皓  阅读(89)  评论(0)    收藏  举报