算法 中等 | 34. N皇后问题 II

算法 中等 | 34. N皇后问题 II

题目描述

根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。

样例1

输入: n=1
输出: 1
解释:
1:
1

样例2

输入: n=4
输出: 2
解释:
1:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
2:
0 1 0 0 
0 0 0 1
1 0 0 0
0 0 1 0

java题解

dfs暴力搜索即可

public class Solution {
    public static int sum;
    public int totalNQueens(int n) {
        sum = 0;
        int[] usedColumns = new int[n];
        placeQueen(usedColumns, 0);
        return sum;
    }
    public void placeQueen(int[] usedColumns, int row) {
        int n = usedColumns.length;
        
        if (row == n) {
            sum ++;
            return;
        }
        
        for (int i = 0; i < n; i++) {
            if (isValid(usedColumns, row, i)) {
                usedColumns[row] = i;
                placeQueen(usedColumns, row + 1);
            }
        }
    }
    public boolean isValid(int[] usedColumns, int row, int col) {
        for (int i = 0; i < row; i++) {
            if (usedColumns[i] == col) {
                return false;
            }
            if ((row - i) == Math.abs(col-usedColumns[i])) {
                return false;
            }
        }
        return true;
    }
}

C++题解

dfs暴力搜索即可

class Solution {
public:
    int sum;
    
    bool canPut(int row, int col, vector<int> &cols) {
        for (int i = 0; i < row; i++) {
            if (cols[i] - i == col - row) {
                return false;
            }
            if (cols[i] + i == col + row) {
                return false;
            }
            if (cols[i] == col) {
                return false;
            }
        }
        return true;
    }
    
    void dfs(int n, int k, vector<int> &cols) {
        if (k == n) {
            sum++;
            return;
        }
        
        for (int i = 0; i < n; i++) {
            if (!canPut(k, i, cols)) {
                continue;
            }
            cols[k] = i;
            dfs(n, k + 1, cols);
        }
    }
    
    int totalNQueens(int n) {
        vector<int> cols(n);
        
        sum = 0;
        dfs(n, 0, cols);
        return sum;
    }
};

python题解

dfs暴力搜索即可

class Solution:
    total = 0
    n = 0

    def attack(self, row, col):
        for c, r in self.cols.iteritems():
            if c - r == col - row or c + r == col + row:
                return True
        return False

    def search(self, row):
        if row == self.n:
            self.total += 1
            return
        for col in range(self.n):
            if col in self.cols:
                continue
            if self.attack(row, col):
                continue
            self.cols[col] = row
            self.search(row + 1)
            del self.cols[col]

    def totalNQueens(self, n):
        self.n = n
        self.cols = {}
        self.search(0)
        return self.total
发布了157 篇原创文章 · 获赞 20 · 访问量 8447

猜你喜欢

转载自blog.csdn.net/qq_43233085/article/details/104092122