题解 | #N皇后问题#

N皇后问题

http://www.nowcoder.com/practice/c76408782512486d91eea181107293b6

class Solution {//参考大佬的Java代码,C++实现
public:
    /**
     * 
     * @param n int整型 the n
     * @return int整型
     */
    int Nqueen(int n) {//递归回溯
        // write code here
        vector<string> rst;
        vector<vector<char>> chess(n,vector<char>(n,'Z'));
        solve(rst, chess, 0, n);
        int len = rst.size();
        return len;
    }
    void solve(vector<string> &rst, vector<vector<char> > chess, int row, int n)
    {
        if(row == n) 
        {
            rst.emplace_back(convert(chess));
            return;
        }
        for(int col = 0; col < n; ++col)
        {
            if(valid(chess, row, col))
            {
                chess[row][col] = 'Q';
                solve(rst, chess, row+1, n);
                chess[row][col] = 'Z';
            }
        }
    }
    
    string convert(vector<vector<char> > chess) //就是放便可视化展示结果
    {
        string rst;
        int len = chess.size();
        for(int i = 0; i < len; ++i)
        {
            string *temp = new string(chess[i].begin(),chess[i].end());
            rst = rst + "\n"+ *temp;
        }
        return rst;
    }
    
    bool valid(vector<vector<char> > chess, int r, int c)
    {
        
        int col = chess[0].size();
        for(int i = r - 1 , j = c + 1; i >= 0 && j < col; i--, j++)//右上角
        {
            if(chess[i][j] ==  'Q') return false;
        }
        
        for(int i = r -1 , j = c -1; i >= 0 && j >= 0; i--, j--) //左上角
        {
            if(chess[i][j] == 'Q') return false;
        }
        for( int i = r-1; i >= 0; i--) //同一列
        {
            if(chess[i][c] == 'Q') return false;
        }
        return true;
    }
};
全部评论

相关推荐

🎓学历背景:双非土木硕👨‍💻意向职位:AI应用开发大佬们可以帮我看看简历吗,秋招至今0offer
秋招结束再玩瓦:今年科班都不好找哇……你可以试试交叉岗,比如制造业国企的一些开发算法,或者互联网的边缘岗,it技术支持,运维这些
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务