C/C++教程

刷题:LC51 N皇后 回溯法

本文主要是介绍刷题:LC51 N皇后 回溯法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、代码
如下代码可以直接在VS上跑起来。

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Solution {
public:
    vector<vector<string>> res;
    vector<vector<string>> solveNQueens(int n) {
        vector<string> board(n, string(n, '.'));
        backtrack(board, 0);
        return res;
    }

    void backtrack(vector<string>& board, int row) {
        //触发结束条件
        if (row == board.size()) {
            res.push_back(board);
            return;
        }
        int n = board[row].size();
        for (int col = 0; col < n; col++) {
            //排除不合法的选择
            if (!isValid(board, row, col))
                continue;
            //做选择
            board[row][col] = 'Q';
            //进入下一行决策
            backtrack(board, row + 1);
            //撤销选择
            board[row][col] = '.';
        }
    }

    bool isValid(vector<string>& board, int row, int col) {
        int n = board.size();
        //检查列中是否有皇后互相冲突
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 'Q')
                return false;
        }
        //检查右上方是否有皇后互相冲突
        for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (board[i][j] == 'Q')
                return false;
        }
        //检查左上方是否有皇后互相冲突
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 'Q')
                return false;
        }
        return true;
    }
};

int main() 
{
    int n = 5;
    vector<vector<string>> res;
    Solution solutrion;
    res = solutrion.solveNQueens(n);
    for (int i = 0; i < res.size(); i++) {
        for (int j = 0; j < res[i].size(); j++) {
                cout << res[i][j] << endl;
        }
        cout << endl;
        cout << endl;
    }
    cout << res.size() << endl;

	return 0;
}

2、运行结果
当n=5时,总共有10种情况,如下图所示。
在这里插入图片描述

这篇关于刷题:LC51 N皇后 回溯法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!