Leetcode 51. N-Queens

原题:

The n-queens puzzle is the problem of placing n queens on ann×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.."]
]

解决方法:

解题的基本思路是:用一个数组来保存queen所在位置的列号,数组的序号表示queen的行号。从一行开始,尝试着往里面放一个合法的列,如果可以,接着处理下一行,直到所有的结果求出。

- 首先需要一个判断列是否合理的函数,检查现有数组,列不能存在,同时新的列号行号与原来的不能在同一对角线上。

- 需要一个将数组转换成结果字符串的函数。

- 最后就是最主要的dfs函数了,处理好返回和循环。


代码:
vector<string> format(vector<int>& queens){
        vector<string> res;
        for(auto col: queens){
            string line;
            for(int i = 0; i < col; i++)
                line.push_back('.');
            line.push_back('Q');
            for(int i = col + 1; i < queens.size(); i++)
                line.push_back('.');
            res.push_back(line);
        }
        
        return res;
    }
    
    
    bool isValid(vector<int>& queens, int row, int col){
        for(int i = 0; i < queens.size(); i++){
            if (queens[i] == -1)
                continue;
            
            if (queens[i] == col)
                return false;
            
            if (abs(i-row) == abs(col-queens[i]))
                return false;
        }
        return true;
    }
    
    void dfs(vector<vector<string>>& res, vector<int> queens, int row, bool reset){
        if (row >= queens.size()){
            res.push_back(format(queens));
            return;
        }
        
        for(int i = 0; i < queens.size();i++){
            if (reset){
                for(auto &p: queens)
                    p = -1;
            }
            if (isValid(queens, row, i)){
                queens[row] = i;
                dfs(res, queens, row + 1, false);
            }
        }
    }
    
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<int> queens(n, -1);
        dfs(res, queens, 0, true);
        return res;
    }





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值