knakul853

Untitled

Jul 17th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     vector<vector<string>> solveNQueens(int n) {
  7.        
  8.         vector<vector<string>>ans;
  9.         vector<string>temp(n, string(n, '.'));
  10.        
  11.         dfs(n, 0, ans, temp );
  12.        
  13.         return ans;
  14.     }
  15.    
  16.     void dfs(int n, int id, vector<vector<string>>&ans, vector<string>&temp)
  17.     {
  18.         if( id == n ){
  19.             ans.push_back(temp);
  20.             return;
  21.         }
  22.        
  23.         for(int i=0;i<n;i++)
  24.         {
  25.             if(ok(temp, id, i, n)){
  26.                 temp[id][i] = 'Q';
  27.                
  28.                 dfs(n, id+1, ans, temp);
  29.                
  30.                 temp[id][i] = '.';
  31.             }
  32.         }
  33.     }
  34.    
  35.     bool ok( vector<string>& dp, int row, int col, int n){
  36.        
  37.         for( int i=0;i<row;i++ ){
  38.             if( dp[i][col] == 'Q' ) return false;
  39.         }
  40.        
  41.         for(int i=row-1 , j = col-1; i>=0 && j>=0; i--,j--){
  42.             if(dp[i][j] == 'Q') return false;
  43.         }
  44.        
  45.         for(int i=row-1, j = col+1;i >=0 && j<n ; i--, j++)
  46.         {
  47.             if( dp[i][j] == 'Q') return false;
  48.         }
  49.        
  50.         return true;
  51.        
  52.     }
  53. };
Add Comment
Please, Sign In to add comment