Leetcode---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.

著名的n皇后问题,要求记录摆放位置,下面几行是关键:

void dfs(int level){
    if(level==N){
        output();
    }
    else{
        for(int i=0;i<N;i++){
            if(check(level+1,i+1)){
                m[level][i]=1;
                dfs(level+1);
                m[level][i]=0;
            }
        }
    }
}
vector<vector<int> > m是全局变量,用来记录遍历轨迹,遍历前设上值,遍历后去掉。每一次调到output的时候,所有压入栈中的函数返回,都会调到
m[level][i]=0;此时m清零。
<pre name="code" class="cpp">int N;
vector<vector<int> > m;
vector<vector<string> > result;
bool check(int row,int column){
            if(row==1) return true;
            int i,j;
            for(i=0;i<=row-2;i++){
                if(m[i][column-1]==1) return false;
            }
            i = row-2;
            j = i-(row-column);
            while(i>=0&&j>=0){
                if(m[i][j]==1) return false;
                i--;
                j--;
            }
            i = row-2;
            j = row+column-i-2;
            while(i>=0&&j<=N-1){
                if(m[i][j]==1) return false;
                i--;
                j++;
            }
            return true;
        }
void output()
{
    vector<string> vec;
    for(int i=0;i<N;i++){
        string s;
        for(int j=0;j<N;j++){
            if(m[i][j]==1)
                s.push_back('Q');
            else
                s.push_back('.');
        }
        vec.push_back(s);
    }
    result.push_back(vec);
}
void dfs(int level){
    if(level==N){
        output();
    }
    else{
        for(int i=0;i<N;i++){
            if(check(level+1,i+1)){
                m[level][i]=1;
                dfs(level+1);
                m[level][i]=0;
            }
        }
    }
}
vector<vector<string> > solveNQueens(int n) {
    N=n;
    for(int i=0;i<n;i++){
        vector<int> a(n,0);
        m.push_back(a);
    }
    dfs(0);
    return result;
}


 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值