【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:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<int> cols(n, 0);
        
        string cur(n, '.');
        vector<string> tmp(n, cur);
        dfs(res, n, cols, 0, tmp);
        return res;
    }
    
    void dfs(vector<vector<string>>& res, int n, vector<int>& cols, int cnt, vector<string>& tmp) {
        if (cnt == n) {
            vector<string> cur(tmp.begin(), tmp.end());
            res.push_back(cur);
            return;
        }
        
        for (int i=0; i<n; ++i) {
            if (cols[i]) continue;
            if (check(n, cnt, i, tmp) == false) continue;
            cols[i] = 1;
            tmp[cnt][i] = 'Q';
            dfs(res, n, cols, cnt+1, tmp);
            tmp[cnt][i] = '.';
            cols[i] = 0;
        }
        
        return;
    }
    
    bool check(int n, int x, int y, vector<string>& tmp) {
        int tx = x, ty = y;
        while(tx >= 0 && ty >= 0) {
            if (tmp[tx--][ty--] == 'Q') return false;
        }
        int sum = x + y;
        for (int i=0; i<x; ++i) {
            if (tmp[i][sum-i] == 'Q') return false;
        }
        return true;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章