Leetcode51. N-Queens

Leetcode51. 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.."]
]


题目分析:
由于最近在上人工智能的课,涉及到八皇后的问题,所以找点八皇后的题来刷。

代码:
class Solution {
public:
    vector<vector<vector<int>>> res;
    vector<vector<string>> solveNQueens(int n) {
        vector<int> t(n);
        vector<vector<int>> k(n, t);
        queens(k, 0);
        return change(res);
    }

    void queens(vector<vector<int>> k, int row) {
        for (int i = 0; i < (int)k.size(); i++) {
            if (check(k, i, row)) {
                k[row][i] = 1;
                if (row == (int)(k.size() - 1)) {
                    res.push_back(k);
                    k[row][i] = 0;
                    return;
                }
                queens(k, row+1);
                k[row][i] = 0;

            }
        }
    }

    bool check(vector<vector<int>> map,int col, int row) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < (int)map.size(); j++) {
                if (map[i][j]) {
                    if (abs(i - row) == abs(j - col)) {
                        return false;
                    }
                    if (j == col)
                        return false;
                }
            }
        }
        return true;
    }

    vector<vector<string>> change(vector<vector<vector<int>>> res) {
        std::vector<string> v;
        vector<vector<string>> k;
        //vector<vector<int>> t;
        string tmp = "";
        for (auto i:res) {
            for (auto j : i) {
                for (auto k : j) {
                    if (k == 0) {
                        tmp.push_back('.');
                    } else {
                        tmp.push_back('Q');
                    }
                }
                v.push_back(tmp);
                tmp = "";
            }
            k.push_back(v);
            v.clear();
        }
        return k;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值