N-Queens

N皇后问题


  • 问题描述:leetcode:51
  • [https://leetcode.com/problems/n-queens/][1]
    N-Queens

思路:

  • 利用回溯法。
  • 一行一行往下遍历,在每行中又看每一列中的位置是否与之前的放Q的位置形成冲突。
  • 冲突又四种:同行、同列、正斜线、反斜线。
  • 同行不需要考察,因为当一行中放了一个Q时,进行下一行的遍历了。
  • 在进行下一行遍历的函数后面,把放置的Q的那个位置还要重新放“.”;因为还要考察本行后面的位置是否还可以形成答案。

按照思路写的代码:

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > res;//解的集合
        vector<string> nQueens(n, string(n, '.'));//其中一个解
        solveNQueens(res, nQueens, 0, n);//从第0行开始遍历
        return res;
    }
    void solveNQueens(vector<vector<string> > &res, vector<string> &nQueens, int row, int &n) {
        if (row == n) {//当一行一行遍历,到达最后一行后,说明找到一个合格的解,把该解push到解的集合中
            res.push_back(nQueens);
            return;
        }
        for (int col = 0; col != n; ++col)
            if (isValid(nQueens, row, col, n)) {
                nQueens[row][col] = 'Q';//当位置合格时,放置Q;
                solveNQueens(res, nQueens, row + 1, n);
                nQueens[row][col] = '.';//当本位置以下所有的行中所有的解都解出来后,要把该行重新设置为“.”,以便查看本行后面的位置是否还有可以的位置
            }
    }
    bool isValid(vector<string> &nQueens, int row, int col, int &n) {
        //check if the column had a queen before.
        for (int i = 0; i != row; ++i)
            if (nQueens[i][col] == 'Q')
                return false;
        //check if the 45° diagonal had a queen before.
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
            if (nQueens[i][j] == 'Q')
                return false;
        //check if the 135° diagonal had a queen before.
        for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j)//注意: i >= 0 && j < n
            if (nQueens[i][j] == 'Q')
                return false;
        return true;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值