跟N-Queens几乎没差别,好像还更简单了呢
代码:
1 int solve(int row, vector<bool> &col, vector<bool> left, vector<bool> right) { 2 if (row == 0) 3 return 1; 4 5 vector<bool> avail(col.size(), false); 6 for (int i = 0; i < col.size(); i++) 7 avail[i] = !(col[i] || left[i] || right[i]); 8 9 for (int i = 0; i < col.size() - 1; i++) 10 left[i] = left[i + 1]; 11 left[col.size() - 1] = false; 12 for (int i = col.size() - 1; i > 0; i--) 13 right[i] = right[i - 1]; 14 right[0] = false; 15 16 int res = 0; 17 for (int i = 0; i < col.size(); i++) { 18 if (!avail[i]) 19 continue; 20 col[i] = true; 21 if (i > 0) left[i - 1] = true; 22 if (i < col.size() - 1) right[i + 1] = true; 23 res += solve(row - 1, col, left, right); 24 if (i < col.size() - 1) right[i + 1] = false; 25 if (i > 0) left[i - 1] = false; 26 col[i] = false; 27 } 28 29 return res; 30 } 31 32 int totalNQueens(int n) { 33 vector<bool> col = vector<bool>(n, false); 34 vector<bool> left = vector<bool>(n, false); 35 vector<bool> right = vector<bool>(n, false); 36 return solve(n, col, left, right); 37 }