Wednesday, July 6, 2016

52. N-Queens II

Same idea with “N-Queens”. The only difference is to increase the counter instead of pushing the solution to result.

1:  class Solution {  
2:  private:  
3:    int count;  
4:  public:  
5:    int totalNQueens(int n) {  
6:      count = 0;  
7:      vector<vector<bool>> sol(n, vector<bool>(n, true));  
8:      helper(sol, 0, n);  
9:      return count;  
10:    }  
11:    void helper(vector<vector<bool>> &sol, int row, int n) {  
12:      if (row == n) { count++; return; }  
13:      for (int j = 0; j < n; j++) {  
14:        if (valid(sol, row, j, n)) {  
15:          sol[row][j] = false;  
16:          helper(sol, row+1, n);  
17:          sol[row][j] = true;  
18:        }  
19:      }  
20:    }  
21:    bool valid(vector<vector<bool>> &sol, int row, int col, int n) {  
22:      for (int i = 0; i < row; i++) if (!sol[i][col]) return false;  
23:      for (int i = row-1, j = col-1; i >= 0 && j >=0; i--, j--) if (!sol[i][j]) return false;  
24:      for (int i = row-1, j = col+1; i >= 0 && j < n; i--, j++) if (!sol[i][j]) return false;  
25:      return true;  
26:    }  
27:  };  

No comments:

Post a Comment