LintCode 33 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击(任意两个皇后不能位于同一行,同一列,同一斜线)。

class Solution {
public:
	/*
	 * @param n: The number of queens
	 * @return: All distinct solutions
	 */
	vector > ans;
	vector> solveNQueens(int n) {
		// write your code here
		vector solution;
		backTracing(solution, n);
		return ans;
	}
	void backTracing(vector solution, int n) {
		if (solution.size() == n) {
			translate(solution);
			return;
		}
		for (int i = 0; i < n; i++) {
			if (isValid(solution, i)) {
				vector temp;
				temp = solution;
				temp.push_back(i);
				backTracing(temp, n);
			}
		}

	}
	bool isValid(vector solution, int p) {
		for (int i = 0; i < solution.size(); i++) {
			if (solution[i] == p) return false;
			if (abs((int)(solution.size() - i)) == abs((int)(p - solution[i]))) return false;
		}
		return true;

	}
	void translate(vector solution) {
		vector singleAns;
		for (int i = 0; i < solution.size(); i++) {
			string ansrow;
			for (int j = 0; j < solution.size(); j++) {
				if (solution[i] == j) ansrow += "Q";
				else ansrow += ".";
			}
// 			cout << ansrow << endl;
			singleAns.push_back(ansrow);
		}
// 		cout << endl;
		ans.push_back(singleAns);
	}
};

 

你可能感兴趣的:(LintCode 33 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击(任意两个皇后不能位于同一行,同一列,同一斜线)。)