LeetCode-51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

题解:

class Solution {
public:
  void dfs(vector<vector<string>> &res, vector<vector<bool>> &chess, int n, int i) {
    if (i == n) {
      vector<string> tmp;
      for (int i = 0; i < n; i++) {
        string idx;
        for (int j = 0; j < n; j++) {
          if (chess[i][j] == false) {
            idx.push_back('Q');
          }
          else {
            idx.push_back('.');
          }
        }
        tmp.push_back(idx);
      }
      res.push_back(tmp);
    }
    else {
      for (int j = 0; j < n; j++) {
        if (chess[i][j] == true && checkPos(chess, n, i, j) == true) {
          chess[i][j] = false;
          dfs(res, chess, n, i + 1);
          chess[i][j] = true;
        }
      }
    }
  }
  bool checkPos(vector<vector<bool>> &chess, int n, int x, int y) {
    bool res = true;
    for (int i = 0; i < n; i++) {
      if (i == x) {
        continue;
      }
      res &= chess[i][y];
    }
    int left = x - 1, right = x + 1, up = y - 1, down = y + 1;
    while (left >= 0 && up >= 0) {
      res &= chess[left--][up--];
    }
    while (right < n && down < n) {
      res &= chess[right++][down++];
    }
    left = x - 1, right = x + 1, up = y - 1, down = y + 1;
    while (left >= 0 && down < n) {
      res &= chess[left--][down++];
    }
    while (right < n && up >= 0) {
      res &= chess[right++][up--];
    }
    return res;
  }

  vector<vector<string>> solveNQueens(int n) {
    vector<vector<bool>> chess(n, vector<bool>(n, true));
    vector<vector<string>> res;
    dfs(res, chess, n, 0);
    return res;
  }
};

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/89195402