51. N皇后

class Solution {
    int count;
    List ls;
    int n;
    boolean bool[][];
    public List> solveNQueens(int n) {
        count = 0;
        ls = new LinkedList();
        bool = new boolean[n][n];
        this.n = n;
        dfs(0);
        return ls;
    }
    private void dfs(int x) {
        if (x == n) {
            ArrayList path = new ArrayList();

            for(int i = 0 ; i < n ; i++) {
                StringBuffer stb = new StringBuffer("");
                for(int j = 0 ; j < n ; j++) {
                if(bool[i][j] == true )
                    stb.append("Q");
                else stb.append(".");
                }
                path.add(stb.toString());
            }
            ls.add(path);
            return;
        }
        for (int i = 0; i < n; i++) {
            int temp = x;
            int flag = 0;
            while (temp >= 0) {
                if((i+flag=0&&bool[temp][i-flag])||bool[temp][i])break;
                temp--;
                flag++;
            }
            if(temp==-1) {
                bool[x][i] = true;
                dfs(x+1);
                bool[x][i] = false;
            }
        }
    }
}
全部评论

相关推荐

沟头学院:无关比赛不要写,这样会显着你主次不分,比赛不要撒谎,有哪些就写那些,创新创业建议删除。技能特长可以适当夸大。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务