leetcode 51. N-Queens 回溯算法的应用

  1. N-Queens Add to List QuestionEditorial Solution My Submissions
    Total Accepted: 67411
    Total Submissions: 235847
    Difficulty: Hard
    Contributors: Admin
    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.

回溯算法:
八皇后问题是回溯算法的经典应用之一。回溯算法应用于一些没有明显确定的计算规则的问题有很好的效果。实际上回溯算法就是一种优化的穷举算法,只不过应用穷举算法时,将一些不可能的分支情况排除,然后回溯到之前的岔路口,类似于DFS算法。
下面给出了N皇后问题的回溯算法解答,备注给出了详细解释。

class Solution {
bool canBePlaced(const vector<string> &tmp,int row,int col,int n){//由于我们是按行从上到下放置Queen,所以我们无需考虑同一行以及该位置之后行    
    for(int i = row - 1;i >=0;--i){
        if(col - (row - i) >= 0 && tmp[i][col - (row - i)] == 'Q')//主对角线是否有Queen
        return false;
        if(col + (row - i) < n && tmp[i][col + (row - i)] == 'Q')//次对角线是否有Queen
        return false;
        if(tmp[i][col] == 'Q')//同一列是否有Queen
            return false;        
    }
    return true;
}
void __SolveNQueens(vector<vector<string>> &res,vector<string> &tmp,int row,int n){
    for(int col = 0;col != n;++col){
        if(canBePlaced(tmp,row,col,n)){
            if(row == n - 1){
                tmp[row][col] = 'Q';
                res.push_back(tmp);
                tmp[row][col] = '.';
                return;
            }
            tmp[row][col] = 'Q';
            __SolveNQueens(res,tmp,row + 1,n);
            tmp[row][col] = '.';
        }
    }
}
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<string> tmp(n,string(n,'.'));
        __SolveNQueens(res,tmp,0,n);

        return res;

    }
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值