Easy to Understand 6ms c++ solution


  • 0
    P
    class Solution {
    public:
    int board[20];
        int count=0;
        vector<vector<string> > res;
        vector<vector<string>> solveNQueens(int n) {
             queen(1,n);
            return res;
            
        }
        
        void print(int n)
    {
     int i,j;
     string x;
     vector<string> ans;
    
     for(i=1;i<=n;++i)
     {
      
      for(j=1;j<=n;++j) 
      {
       if(board[i]==j)
        x.push_back('Q'); 
       else
        x.push_back('.'); 
      }
       if(i!=n){
       x.push_back('"'); 
        x.push_back(','); 
        x.push_back('"'); 
        }
     }
     ans.push_back(x);
     res.push_back(ans);
    }
        int place(int row,int column)
        {
            for(int i=1;i<=row-1;i++)
            {
            if(board[i]==column)
            return 0;
            else
       if(abs(board[i]-column)==abs(i-row))
        return 0;
        }
        return 1;
        }
        
        
        void queen(int row, int n)
        {
            int column;
            for(column=1;column<=n;column++)
            {
                if(place(row,column))
                {
                board[row]=column;
                if(row==n)
                print(n);
                else
                queen(row+1,n);
            }
        }
        
        }
        
        
    };
    

Log in to reply
 

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