51.leetcode N-Queens(hard)[递归回溯剪枝]

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

八皇后问题的关键是每个皇后不在同一列同一行,并且不在同一对角线。那么首先我们可以默认每个皇后不在同一行,即每一行一个皇后。用一个状态数组status保存每行的皇后所在的列数,此时对于每个皇后可以放置的列数是0~n-1遍历,并且检查该行之前放置的皇后的列数位数会不会导致当前皇后与其他皇后引起攻击。因此用valid函数检查此行填写的列数是否合法,如果合法则往下走填写后面行的列数,当填写完所有行的列数,此时就得到一个合法的解。但是此时得到的不是string的表达形式,需要通过changeToString函数转换成string的形式。

class Solution {
public:
    void changeToString(vector<int> &status,vector<vector<string> >&result)
    {
        int n = status.size();
        vector<string> temp;
        for(int i=0;i<n;i++)
        {
            string s = "";
            for(int j=0;j<n;j++)
            {
                if(status[i] != j)
                   s += '.';
                else
                   s += 'Q';
            }
            temp.push_back(s);
        }
        result.push_back(temp);
    }
    bool valid(int cols,int row,int n, vector<int> &status)
    {
        for(int i=0;i<row;i++)
        {
            if(status[i] == cols || abs(status[i]-cols) == abs(i-row))
                    return false;
        }
        return true;
    }
    void getQueens(int row,int n,vector<int> &status,vector<vector<string> >&result)
    {
        if(row == n) //此时表示一个合法的皇后棋盘已经产生
        {
            changeToString(status,result);
        }else{
            for(int i= 0;i<n;i++)
            {
                 if(valid(i,row,n,status))   
                 {
                     status[row] = i;
                     getQueens(row+1,n,status,result);
                     status[row] = -1;
                 }
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string> > result;
        if(n <= 0) return result;
        vector<int>status(n,-1);
        getQueens(0,n,status,result);
        return result;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值