
Desicription
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class { private: int res = 0; public: int totalNQueens(int n) { vector<int> state(n, -1); dfs(state, 0); return res; } void dfs(vector<int>& state, int row){ int n = state.size(); if(row == n){ res++; return ; } for(int col = 0; col < n; col++){ if(isVaild(state, row, col)){ state[row] = col; dfs(state, row+1); state[row] = -1; } } } bool isVaild(vector<int>& state, int row, int col){ for(int i = 0; i < row; i++){ if(state[i] == col || abs(row - i) == abs(col - state[i])) return 0; } return 1; } };
|
近期评论