MENU

LeetCode52. N皇后 II

July 14, 2018 • Read: 3086 • LeetCode阅读设置

class Solution {
    public int[] path = new int[100];//path[i]表示第i行的皇后所在第path[i]列
    public int ans = 0;
    public void dfs(int idx,int n) {
        int j;
        if(idx >= n) {
            ans++;
            return;
        }
        for(int i = 0;i < n;i++) {//枚举n列
            for(j = 0;j < idx;j++) {//和前idx行的皇后比较
                if(i == path[j] || Math.abs(i - path[j]) == Math.abs(idx - j))
                    break;
            }
            if(j == idx) {
                path[idx] = i;
                dfs(idx + 1,n);
            }
        }
    }
    public int totalNQueens(int n) {
        ans = 0;
        dfs(0,n);
        return ans;
    }
}
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code