My 4ms C++ solution using DFS,easy to understand,very short 20 lines


  • 0
    H
    class Solution {
    public:
    void dfs(int row,const int n,vector<vector<string>> & ret,vector<string> & vect,int col[],int xy[],int yx[]){
        if(row == n) return ret.push_back(vect);
        for(int i = 0; i < n; i++)
            if(!col[i] && !xy[n + row - i] && !yx[row + i]){
                col[i] = xy[n + row - i] = yx[ row + i] = 1;
                vect[row][i] = 'Q';
                dfs(row + 1,n,ret,vect,col,xy,yx);
                vect[row][i] = '.';
                col[i] = xy[n + row - i] = yx[ row + i] = 0;
            }
    }
    vector<vector<string>> solveNQueens(int n) {
        int col[64]={0},xy[64]={0},yx[64]={0};
        vector<vector<string>> ret;
        vector<string> vect(n,string(n,'.'));
        dfs(0,n,ret,vect,col,xy,yx);
        return ret;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.