lintcode 34 N皇后问题

注意回溯 还有重置为零的步骤

class Solution {
public:
    /*
     * @param n: The number of queens
     * @return: All distinct solutions
     */
    vector> solveNQueens(int n) {
        // write your code here
        vector> res;
        int **queens = new int*[n];
        for(int i = 0;i < n;i++){
            queens[i] = new int[n]();
        }
        
        if(n < 1){
            return res;
        }
        help(res,queens,n,0,0);
        return res;
        
    }
    
    void help(vector> &res,int** queens,int n,int i,int j){
        //i,j表示在二维数组中的位置
        if(i > n-1){         //基本情况,n个皇后已经放好,注意是n-1
            vector line = serilier(queens,n);
            res.push_back(line);
            return;
        }else{
            for(int col = 0;col < n;col++){
                if(ispost(queens,n,i,col)){
                    queens[i][col] = 1;
                    help(res,queens,n,i+1,0);//找下一行
                    queens[i][col] = 0;      //注意还要重置为0
                }
            }
        }
        return;
    }
    
    bool ispost(int** queens,int n,int i,int j){
        for(int row = 0;row < i;row++){
            if(queens[row][j] == 1){
                return false;
            }
        }
        for(int col = 0;col < j;col++){
            if(queens[i][col] == 1){
                return false;
            }
        }
        for(int row = i,col = j; row >=0 && col >=0;row--,col--){
            if(queens[row][col] == 1){
                return false;
            }
        }
        for(int row = i,col = j; row >=0 && col  serilier(int** queens,int n){
        vector res;
        for(int i= 0;i < n;i++){
            string l;
            for(int j= 0;j < n;j++){
                if(queens[i][j] == 0){
                    l += ".";
                }else{
                    l +="Q";
                }
            }
            res.push_back(l);
        }
        return res;
    }
};

你可能感兴趣的:(lintcode 34 N皇后问题)