leetcode_51. N皇后

1. 题意描述

原题链接

2. 题意分析

我以八皇后为例进行分析. 

主要有三种思路

  1. 思路一: 暴力出奇迹
    1. 64种格子中选出任意8个格子拜访皇后, 检查每一种摆法的可能性
    2. 一共C_{64}^8种摆法 (大概是4.4 \times 10^9种摆法)
  2. 思路二: 根据题意减小暴力程度
    1. 很显然, 每一行只能放一个皇后, 所以共有8^8种摆法 (16777216种), 检查每一种摆法的可能性
  3. 思路三: 回溯法
    1. 回溯 + 剪枝

3. AC Code

int Q[10] = { 0 };  // 存放每一个皇后的列号
int ways = 0;  // 解法数
vector<vector<string>> ans;

class Solution {
public:
    bool isValid(int row, int col) {
        // 检查第row行第col列是否可以放置皇后
        for (int i = 0; i < row; i++) {
            if (Q[i] == col) return false;
            if (row - i == abs(col - Q[i])) return false;
        }
        return true;
    }

    void place(int row, int n, vector<vector<string>>& ans) {
        // 从第row行开始放置皇后
        if (row == n) {
            vector<string> tmp;
            for (int i = 0; i < n; i++) {
                string s;
                for (int j = 0; j < Q[i]; j++) s += ".";
                s += "Q";
                for (int j = Q[i] + 1; j < n; j++) s += ".";
                tmp.push_back(s);
            }
            ans.push_back(tmp);
            return;
        }
        for (int col = 0; col < n; col++) {
            if (isValid(row, col)) {
                Q[row] = col;
                place(row + 1, n, ans);
            }
        }
    }

    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> ans;
        place(0, n, ans);
        return ans;
    }
};

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值