题解 | #N皇后问题#

N皇后问题

https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6

import java.util.*;


public class Solution {

    private Set<Integer> colSet = new HashSet<>();
    private Set<Integer> posSet = new HashSet<>();
    private Set<Integer> nagSet = new HashSet<>();
    private int res = 0;

    /**
     * 
     * @param n int整型 the n
     * @return int整型
     */
    public int Nqueen (int n) {
        // write code here
        if (n < 1) {
            return 0;
        }
        backTrack(0, n);
        return res;
    }

    private void backTrack(int i, int n) {
        if (i == n) {
            res++;
            return;
        }
        for (int j = 0; j < n; j++) {
            if (colSet.contains(j) || posSet.contains(i - j) || nagSet.contains(i + j)) {
                continue;
            }
            colSet.add(j);
            posSet.add(i - j);
            nagSet.add(i + j);
            backTrack(i + 1, n);
            colSet.remove(j);
            posSet.remove(i - j);
            nagSet.remove(i + j);
        }
    }
}

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务