LeetCode 51 N-Queens

题意:

n皇后问题,输出n*n的棋盘摆放n个皇后的方案。

皇后攻击方式为同一行、同一列、同一斜线。


思路:

直接搜索。空间消耗方面,不需要申请整个棋盘大小,只要O(n)就够了,存某一行的皇后放在哪一列。


代码:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        int *column = new int[n];
        vector<vector<string>> ans;
        dfs(0, n, column, ans);
        return ans;
    }

private:
    void dfs(int row, int total, int *column, vector<vector<string>> &ans) {
        if (row == total) {
            vector<string> part;
            for (int i = 0; i < total; ++i) {
                stringstream ss;
                for (int j = 0; j < total; ++j) {
                    if (column[i] == j) {
                        ss << 'Q';
                    } else {
                        ss << '.';
                    }
                }
                part.push_back(ss.str());
            }
            ans.push_back(part);
            return;
        }
        for (int i = 0; i < total; ++i) {
            bool can = true;
            for (int j = 0; j < row; ++j) {
                if (i == column[j] || i == column[j] - (row - j) || i == column[j] + (row - j)) {
                    can = false;
                    break;
                }
            }
            if (can) {
                column[row] = i;
                dfs(row + 1, total, column, ans);
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值