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

vector<int> nums(n);num[i]表示第i行的queen放在num[i]列,这样就转化成求0-n-1的全排列,然后看每一个排列是否符合条件。

vector<vector<string>> res;
	void permutationHelper(vector<int> &nums, int index, int n)
	{
		if(index == n)
		{
			bool flag = true;
			for(int i = 0; i<n && flag; i++)
				for(int j=i+1; j<n; j++)
					if((j-i) == abs(nums[j]-nums[i]))
					{
						flag = false;
						break;
					}

			if(flag)
			{
				vector<string> tmp;
				for(int i =0; i<n;i++)
				{
					string row(n,'.');
					row[nums[i]]='Q';
					tmp.push_back(row);
				}
				res.push_back(tmp);
			}
		}
		for(int i = index; i < n; i++)
		{
			swap(nums[index], nums[i]);
			permutationHelper(nums, index+1, n);
			swap(nums[index], nums[i]);
		}
	}
	void permutation(int n)
	{
		vector<int> nums(n);
		for(int i = 0; i < n; i++)
			nums[i] = i;
		permutationHelper(nums,0,n);
	}
	vector<vector<string> > solveNQueens(int n) {
        // Note: The Solution object is instantiated only once.
        res.clear();
		permutation(n);
		return res;
    }





你可能感兴趣的:(LeetCode,N,permutation,Queens)