【leetcode】N-Queens

class Solution {

    vector<vector<string> > ans;

public:

    bool canPlace(int i,int j,vector<string> &tmp,int n)//check 
    {
        if(i==0) return true;//when place the first line,all cols is OK 
        for(int k=0;k<=i-1;k++)//check the lines already placed
            if(tmp[k][j]=='Q')
                return false;
        for(int p=0;p<=i-1;p++)//line:already placed from 0 to i-1
            for(int q=0;q<=n-1;q++)//col:from 0 to n-1
                if( (p-q==i-j || p+q==i+j)
                    &&(tmp[p][q]=='Q') )//135 and 45
                    return false;
        return true;
    }
    
    vector<int> findCols(int i,vector<string> &tmp,int n)//when line is i,find all possible cols
    {
        vector<int> res;
        for(int k=0;k<=n-1;k++)
        {
            if(canPlace(i,k,tmp,n))
                res.push_back(k);
        }
        return res;
    }
    
    void dfs(int level,vector<string> &tmp,int n)//dfs
    {
        if(level >= n){
            ans.push_back(tmp);
            return;
        }
        
        vector<int> posCols = findCols(level, tmp, n);
        int col;
        for(int k = 0; k < posCols.size(); k++){
            //cannot use k<=posCols.size()-1,otherwise will occur runtime error
            col = posCols[k];
            tmp[level][col] = 'Q';//do
            dfs(level + 1, tmp, n);
            tmp[level][col] = '.';//undo
        }
    }
        
    vector<vector<string> > solveNQueens(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        ans.clear();
        vector<string> tmp(n, string(n,'.'));//string(n,'.') means set one line as '....',and tmp is n*n '.'
        dfs(0,tmp,n);
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值