Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

N皇后 #55

Open
louzhedong opened this issue Sep 10, 2018 · 0 comments
Open

N皇后 #55

louzhedong opened this issue Sep 10, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第51题

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

img

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q''.' 分别代表了皇后和空位。

示例:

输入: 4
输出: [
 [".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。

思路

采用回溯法,遍历所有的可能性,输出结果

解答

/**
 * @param {number} n
 * @return {string[][]}
 */

function isSafe(array, n, x, y) {
  for (var i = 0; i < n; i++) {
    for (var j = 0; j < y; j++) {
      if (array[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i)) {
        return false;
      }
    }
  }

  return true;
}

function solve(array, col, result, n) {
  if (col == n) {
    var temp = [];
    for (var i = 0; i < n; i++) {
      temp.push(array[i].join(''));
    }
    result.push(temp);
    return;
  }

  for (var i = 0; i < n; i++) {
    if (isSafe(array, n, i, col)) {
      array[i][col] = 'Q';
      solve(array, col + 1, result, n);
      array[i][col] = '.'
    }
  }
}

var solveNQueens = function (n) {
  var result = [];
  var array = [];
  for (var i = 0; i < n; i++) {
    array[i] = [];
    for (var j = 0; j < n; j++) {
      array[i][j] = '.';
    }
  }
  solve(array, 0, result, n);

  return result;
};

console.log(solveNQueens(4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant