LeetCode 题解(104): N-Queens

题目:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

题解:

C++版:

class Solution {
private:
    vector<vector<string>> results; 
public:
    vector<vector<string> > solveNQueens(int n) {
        if(n == 0)
            return results;
        vector<int> location(n, -1);
        trace(location, 0, n);
        return results;
    }
    
    void trace(vector<int>& location, int level, int n) {
        if(level == n) {
            vector<string> res(n, string(n, '.'));
            for(int i = 0; i < n; i++) {
                res[i][location[i]] = 'Q';
            }
            results.push_back(res);
            return;
        }
        for(int i = 0; i < n; i++) {
            if(isValid(location, level, i)) {
                location[level] = i;
                trace(location, level + 1, n);
                location[level] = -1;
            }
        }
    }
    
    bool isValid(vector<int>& location, int row, int col) {
        for(int i = 0; i < row; i++) {
            if(location[i] == col || abs(row - i) == abs(location[i] - col))
                return false;
        }
        return true;
    }
};

Java版:

public class Solution {
    private List<String[]> results;
    public List<String[]> solveNQueens(int n) {
        if(n == 0)
            return results;
        int[] location = new int[n];
        for(int i = 0; i < n; i++)
            location[i] = -1;
        trace(location, n, 0);
        return results;
    }
    
    private void trace(int[] location, int n, int level) {
        if(level == n) {
            String[] res = new String[n];
            for(int i = 0; i < n; i++) {
                StringBuilder s = new StringBuilder();
                for(int j = 0; j < n; j++) {
                    if( j == location[i])
                        s.append("Q");
                    else
                        s.append(".");
                }
                res[i] = s.toString();
            }
            results.add(res);
            return;
        }
        for(int i = 0; i < n; i++) {
            if(isValid(location, level, i)) {
                location[level] = i;
                trace(location, n, level + 1);
                location[level] = -1;
            }
        }
    }
    
    private boolean isValid(int[] location, int row, int col) {
        for(int i = 0; i < row; i++) {
            if(location[i] == col || Math.abs(row - i) == Math.abs(location[i] - col))
                return false;
        }
        return true;
    }
}

Python版:

class Solution:
    # @return a list of lists of string
    def solveNQueens(self, n):
        results = []
        if n == 0 or n == 2:
            return results
        location = [-1 for i in range(n)]
        def trace(location, n, level):
            if level == n:
                res = [('.' * n) for i in range(n)]
                for i in range(n):
                    res[i] = res[i][0:location[i]] + 'Q' + res[i][location[i] + 1:]
                results.append(res)
                return
            for i in range(n):
                if isValid(location, level, i):
                    location[level] = i
                    trace(location, n, level+1)
                    location[level] = -1
        def isValid(location, row, col):
            for i in range(row):
                if location[i] == col or abs(row - i) == abs(location[i] - col):
                    return False
            return True
        trace(location, n, 0)
        return results


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值