LeetCode 51: N-Queens

class Solution {
public:
    Solution()
    {
        for(int i=0; i<16; i++)
            arr[i] = 0;
    }
    vector<vector<string>> solveNQueens(int n) 
    {
        vector<vector<string>> vecRes;
        vector<string> board(n, string(n, '.'));
        
        fun(vecRes, board, 0);
        
        return vecRes;
    }
    
private:
    void fun(vector<vector<string>>& result, vector<string>& board, int curRow)
    {
        int size = board.size();
        for(int col=0; col<size; col++)
        {
            if(isValid(board, curRow, col))
            {
                board[curRow][col] = 'Q';
                arr[col] = 1;
                
                if(curRow == size-1)
                    result.push_back(board);
                else
                    fun(result, board, curRow+1);
                    
                board[curRow][col] = '.';
                arr[col] = 0;
            }            
        }
    }
    
    bool isValid(vector<string>& board, int i, int j)
    {
        int size = board.size();
        int row = 0;
        int col = 0;
        
        if(arr[j] == 1)
            return false;
        
        for(row=i-1, col=j-1; row>=0&&col>=0; row--,col--)
            if(board[row][col] == 'Q')
                return false;
        for(row=i-1, col=j+1; row>=0&&col<size; row--,col++)
            if(board[row][col] == 'Q')
                return false;
                
        return true;
    }
    
    int arr[16];
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值