设为首页 加入收藏

TOP

[leetcode]N-Queens
2014-11-23 21:42:27 来源: 作者: 【 】 浏览:11
Tags:leetcode N-Queens
class Solution {
    vector> result;
public:
    bool canPlace(int i, int j, vector &tmp, int n){
        if(i == 0) return true;
        for(int k = 0; k < i; k++){
            if(tmp[k][j] == 'Q') return false;
        }
        for(int p = 0; p < i; p++){
            for(int q = 0; q < n; q++){
                if((p-q == i-j || p+q == i+j) && tmp[p][q] == 'Q'){
                    return false;
                }
            }
        }
        return true;
    }

    vector possiblePlaces(int i, vector &tmp, int n){
        vector places;
        
        for(int j = 0; j < n; j++){
            if(canPlace(i,j,tmp, n)){
                places.push_back(j);
            }
        }
        return places;
    }
    
    void dfs(int level, vector &tmp, int n){
        if(level >= n){
            result.push_back(tmp);
            return;
        }
        
        vector places = possiblePlaces(level, tmp, n);
        int j;
        for(int k = 0; k < places.size(); k++){
            j = places[k];
            tmp[level][j] = 'Q';
            dfs(level + 1, tmp, n);
            tmp[level][j] = '.';
        }
        
    }

    vector > solveNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result. clear();
        vector tmp(n, string(n, '.'));
        dfs(0, tmp, n);
        
        return result;
    }
};

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 2051 Bitset 下一篇HDU 多校第三场

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·【C语言】动态内存管 (2025-12-27 06:23:20)
·C语言中的内存管理 - (2025-12-27 06:23:16)
·C语言指南:C语言内 (2025-12-27 06:23:14)
·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)