题意:

image.png
image.png

图解:

image.png

解题思路:

  1. 思路:
  2. 1. 枚举每一个位置,并将该位置放入竖,撇,捺数组中;
  3. 2. 枚举下一个位置之前,看该位置对应的竖,撇,捺是否已经有值;
  4. 3. 如果有值,则表示冲突,跳过,继续尝下下一个位置,直到遍历到最后一个位置;
  5. 4. 继续下一层枚举;

PHP代码实现:

  1. class Solution {
  2. public $cols = [];//列
  3. public $pie = [];
  4. public $na = [];
  5. public $res = [];
  6. function solveNQueens($n) {
  7. $this->solve([], $n, 0);
  8. return $this->generateAnswer($n);
  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)
  17. || in_array($i - $j + $n, $this->na)) continue;
  18. array_push($this->cols, $j);
  19. array_push($this->pie, $i + $j);
  20. array_push($this->na, $i - $j + $n);
  21. $answer[$i] = $j;
  22. $this->solve($answer, $n, $i + 1);
  23. array_pop($this->cols);
  24. array_pop($this->pie);
  25. array_pop($this->na);
  26. }
  27. }
  28. function generateAnswer($n) {
  29. $ret = [];
  30. foreach ($this->res as $v) {
  31. for ($i = 0; $i < $n; $i++) {
  32. $str = "";
  33. foreach ($v as $v1) {
  34. if ($v1 == $i) $str .= "Q";
  35. else $str .= ".";
  36. }
  37. array_push($ret, $str);
  38. }
  39. }
  40. return array_chunk($ret, $n);
  41. }
  42. }

GO代码实现:

  1. func solveNQueens(n int) [][]string {
  2. if n == 0 { return nil}
  3. res := make([][]int, 0)
  4. cols := make(map[int]bool, n)
  5. pie := make(map[int]bool, n)
  6. na := make(map[int]bool, n)
  7. dfs([]int{}, n, cols, pie, na, &res)
  8. return generate(res, n)
  9. }
  10. func dfs(rows []int, n int, cols, pie, na map[int]bool, res *[][]int) {
  11. row := len(rows)
  12. if row == n {
  13. temp := make([]int, len(rows))
  14. copy(temp, rows)
  15. (*res) = append((*res), temp)
  16. return
  17. }
  18. for col := 0; col < n; col++ {
  19. if !cols[col] && !pie[row + col] && !na[row - col] {
  20. cols[col] = true;
  21. pie[row + col] = true;
  22. na[row - col] = true
  23. dfs(append(rows, col), n, cols, pie, na, res)
  24. cols[col] = false
  25. pie[row + col] = false
  26. na[row - col] = false
  27. }
  28. }
  29. }
  30. func generate(res [][]int, n int) (result [][]string) {
  31. for _, v := range res {
  32. var s []string
  33. for _, val := range v {
  34. str := ""
  35. for i := 0; i < n; i++ {
  36. if i == val {
  37. str += "Q"
  38. } else {
  39. str += "."
  40. }
  41. }
  42. s = append(s, str)
  43. }
  44. result = append(result, s)
  45. }
  46. return
  47. }