【LeetCode051】N皇后问题,回溯法,加上一个栈维护结果

同【LeetCode052】

只是要具体的结果,那么只需多用一个全局的栈来存结果,每次找到一个,添加到结果队列ansList里即可


注意,vector > ansList;

>>之间要有一个空格,不然两个>会被认为是>>,会报错

AC代码

#include
#include
#include
#include
using namespace std;

int col[101];
int x1[202];
int x2[202];
int ans = 0;
int ansStack[101];
int top = 0;
vector > ansList;

class Solution {
public:
    vector > solveNQueens(int n) {
		ans = 0;
		top = 0;
		ansList.clear();
        memset(col, 0, sizeof(col));
		memset(x1, 0, sizeof(x1));
		memset(x2, 0, sizeof(x2));
		
		solve(0, n);
		// printf("%d\n", ans);
		return ansList;
    }
	void solve(int ri, int n) {
		if (ri == n) {
			vector oneAns;
			for (int i = 0 ; i < n; i++) {
				string str = "";
				for (int j = 0; j < n; j++) {
					if (j == ansStack[i]) {
						str += "Q";
					} else {
						str += ".";
					}
				}
				oneAns.push_back(str);
			}
			ansList.push_back(oneAns);
			ans++;
			return;
		}
		
		int ci;
		for (ci = 0; ci < n; ci++) {
			if (col[ci] || x1[ri + ci] || x2[ri + n - 1 - ci]) continue;

			col[ci] = 1;
			x1[ri + ci] = 1;
			x2[ri + n - 1 - ci] = 1;
			ansStack[top++] = ci;
			solve(ri + 1, n);
			top--;
			col[ci] = 0;
			x1[ri + ci] = 0;
			x2[ri + n - 1 - ci] = 0;
		}
	}
};

int main() {
	Solution s;
	ansList = s.solveNQueens(4);
	for (int i = 0; i < ansList.size(); i++) {
		for (int j = 0; j < ansList[i].size(); j++){
			cout << ansList[i][j] << endl;
		}
	}
	return 0;
}


你可能感兴趣的:(LeetCode)