题意:

image.png

解题思路:

  1. 思路:
  2. 1. 解法同:51. N皇后

PHP代码实现:

  1. class Solution {
  2. public $cols = [];
  3. public $pie = [];
  4. public $na = [];
  5. public $res = [];
  6. function totalNQueens($n) {
  7. $this->solve([], $n, 0);
  8. return count($this->res);
  9. }
  10. function solve($answer, $n, $i) {
  11. if ($i == $n) {
  12. array_push($this->res, $answer);
  13. return;
  14. }
  15. for ($j = 0; $j < $n; $j++) {
  16. if (in_array($j, $this->cols) || in_array($i + $j, $this->pie) || in_array($i - $j + $n, $this->na)) {
  17. continue;
  18. }
  19. array_push($this->cols, $j);
  20. array_push($this->pie, $i + $j);
  21. array_push($this->na, $i - $j + $n);
  22. $answer[$i] = $j;
  23. $this->solve($answer, $n, $i + 1);
  24. array_pop($this->cols);
  25. array_pop($this->pie);
  26. array_pop($this->na);
  27. }
  28. }
  29. }

GO代码实现:

  1. func totalNQueens(n int) int {
  2. res := make([][]int, 0)
  3. cols := make(map[int]bool, n)
  4. pie := make(map[int]bool, n)
  5. na := make(map[int]bool, n)
  6. dfs([]int{}, n, cols, pie, na, &res)
  7. return len(res)
  8. }
  9. func dfs(rows []int, n int, cols, pie, na map[int]bool, res *[][]int) {
  10. row := len(rows)
  11. if row == n {
  12. temp := make([]int, len(rows))
  13. copy(temp, rows)
  14. (*res) = append((*res), temp)
  15. return
  16. }
  17. for col := 0; col < n; col++ {
  18. if !cols[col] && !pie[row + col] && !na[row - col] {
  19. cols[col], pie[row + col], na[row - col] = true, true, true;
  20. dfs(append(rows, col), n, cols, pie, na, res)
  21. cols[col], pie[row + col], na[row - col] = false, false, false;
  22. }
  23. }
  24. }