[CareerCup] 9.9 Eight Queens 八皇后问题

本文介绍了一种解决八皇后问题的算法实现,通过深度优先搜索(DFS)递归地放置皇后,并确保任意两个皇后不在同一行、列或对角线上。文章提供了完整的C++代码示例。

 

9.9 Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.

 

LeetCode上的原题,请参见我之前的博客N-Queens N皇后问题N-Queens II N皇后问题之二

 

class Solution {
public:
    vector<vector<int> > placeQueens(int n) {
        vector<vector<int> > res;
        vector<int> pos(n, -1);
        placeQueensDFS(pos, 0, res);
        return res;
    }
    void placeQueensDFS(vector<int> &pos, int row, vector<vector<int> > &res) {
        int n = pos.size();
        if (row == n) res.push_back(pos);
        else {
            for (int col = 0; col < n; ++col) {
                if (isValid(pos, row, col)) {
                    pos[row] = col;
                    placeQueensDFS(pos, row + 1, res);
                    pos[row] = -1;
                }
            }
        }
    }
    bool isValid(vector<int> &pos, int row, int col) {
        for (int i = 0; i < row; ++i) {
            if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
                return false;
            }
        }
        return true;
    }
};

 

转载于:https://www.cnblogs.com/grandyang/p/4845827.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值