Leetcode: 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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

搞到很久,一个变量写错了,总是报Memory Limit Exceeded,郁闷。

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        solveNQueensUtil(0, n);
        
        return result;
    }
    
    void solveNQueensUtil(int step, int n) {
        if (step == n) {
            print(n);
            return;
        }
        
        for (int i = 0; i < n; ++i) {
            cols.push_back(i);
            if (canPutQueen(step)) {
                solveNQueensUtil(step + 1, n);
            }
            cols.pop_back();
        }
    }
    
    bool canPutQueen(int step) {
        for (int i = 0; i < step; ++i) {
            if (cols[step] == cols[i] || abs(step - i) == abs(cols[step] - cols[i])) {
                return false;
            }
        }
        
        return true;
    }
    
    void print(int n) {
        vector<string> solve;
        for (int i = 0; i < n; ++i) {
            string line;
            for (int j = 0; j < n; ++j) {
                line.push_back(cols[i] == j ? 'Q' : '.');
            }
            solve.push_back(line);
        }
        result.push_back(solve);
    }
    
private:
    vector<int> cols;
    vector<vector<string> > result;
};

你可能感兴趣的:(LeetCode)