Leetcode 51. N-Queens

51. N-Queens

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.."]
]
题目链接:https://leetcode.com/problems/n-queens/description/
题目大意:n皇后问题,在n * n的棋盘上,摆放n个皇后,是同行同列以及两条同斜边不同时出现两个皇后。列出所有方案。
解题思路:裸dfs摆放皇后位置。
代码如下:
class Solution {
private:
    vector<vector<string> > ans;
    char a[1000][1000]; //表示棋盘
    int vis[10000];  //判断列是否重复
public:
    bool ok(int n,int x,int y){  //判断斜边上没有其他皇后(左斜上、左斜下、右斜上、右斜下四个方向遍历)
        for(int i = x + 1,j = y + 1;i < n && j < n ; i ++,j++ ){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x - 1,j = y - 1;i >= 0 && j >= 0 ;i -- ,j --){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x + 1,j = y - 1;i < n && j >=0 ;i ++ ,j --){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x - 1,j  = y + 1;i >= 0 && j < n;i --,j ++){
            if(a[i][j] == 'Q')
                return false;
        }
        return true;
    }
    void dfs(int n,int x){
        if(x == n){   如果皇后以摆放完,把棋盘数组转换成字符串数组押入答案数组
            vector<string> vt;
            for(int i = 0;i < n;i ++){
                string ns = "";
                for(int j = 0;j < n ;j ++){
                    ns += a[i][j];
                }
                vt.push_back(ns);
            }
            ans.push_back(vt);
            return ;
        }
        for(int i = 0;i < n;i ++){
            if(vis[i] || !ok(n,x,i))
                continue;
            a[x][i] = 'Q';
            vis[i] = 1;
            dfs(n, x + 1);
            vis[i] = 0;
            a[x][i] = '.';
        }
    }
    vector<vector<string> > solveNQueens(int n) {
        for(int i = 0;i < n; i ++){
            for(int j = 0;j < n;j ++){
                a[i][j] = '.';
            }
        }
        dfs(n,0);
        return ans;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值