51. N-Queens

Description:

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.."]
]

Thought:

跟之前的N-Queens的问题相似,只是稍微麻烦了一点。这次在写代码的时候,把进行下一行计算时的k+1写成了++k,导致未找到解时不能正确返回,可以说是很浪费时间去debug了。同时跟上次相比,在每次模拟的时候,记录该行所占的列即可。


Code:

class Solution {
public:
	vector result;
	vector> intResult;
	vector> stringResult;
	vector> solveNQueens(int n) {
		int* rowAndCol = new int[n];
		result = vector(n, 0);
		string temp = string(n, '.');
		findResult(0, n, rowAndCol);
		for (int i = 0; i < intResult.size(); i++) {
			stringResult.push_back(vector(n, temp));
			for (int j = 0; j < n; j++) {
				stringResult[i][j][intResult[i][j]] = 'Q';
			}
		}
		return stringResult;
	}
	void findResult(int k, int n, int rowAndCol[]) {
		if (k == n) {//Are you OK?
			intResult.push_back(result);
			return;
		}
		for (int i = 0; i < n; i++) {
			rowAndCol[k] = i;
			if (check(rowAndCol, k)) {
				result[k] = i;
				findResult(k+1, n, rowAndCol);
			}
		}
	}
	bool check(int rowAndCol[], int rows) {
		for (int i = 0; i < rows; i++) {
			if (rowAndCol[i] == rowAndCol[rows] || abs(rowAndCol[i] - rowAndCol[rows]) == abs(i - rows)) return false;
		}
		return true;
	}
};


你可能感兴趣的:(算法,Algorithms,DP)