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

 

输出所有在n*n的区域内放n个后,每个后都无法相互吃对方(横、竖、斜都没有其他后)。

需要求解每一种情况,

每次放入一个合法的Q,递归求解。

关键在于快速确定一个位置此时放入Q是否合法,从而确定一个可以放入Q的位置,

每个Q会独占一个行,一个列,一个左上到右下的斜线,一个右上到坐下的斜线,

通过标记,记录所有相应的行、列、斜线的占有情况,即可在O(1)时间内确定一个格子此时放入Q是否合法。

 

代码:

class Solution {
	vector<vector<string>> ans;		//结果
	vector<string> board;		//棋盘
	vector<int> frows,fcols,frowcol,fcolrow;	//相应行有Q,列有Q,右下方向斜线有Q,右上方向斜线有Q
public:
    bool isValid(int row,int col,int n)	//判断相应位置是否可以插入Q
	{	
		if(frows[row]==1||fcols[col]==1)	//行有,列有Q
			return false;
		if(frowcol[row-col+n-1]==1)	//线x-y+n-1=i有Q
			return false;
		if(fcolrow[row+col]==1)	//线x+y=i有Q
			return false;
		return true;
	}
	void innerSolve(int row,int col,int n,int num)	//行、列、n、已经插入的Q数
	{
		if(num==n)
			ans.push_back(board);
		else	//寻找之后所有可以插入的位置
		{
			int i,j;
			for(i=row;i<n;i++)
			{
				for(j=0;j<n;j++)
				{
					if(isValid(i,j,n))
					{
						board[i][j]='Q';
						frows[i]=1;
						fcols[j]=1;
						frowcol[i-j+n-1]=1;
						fcolrow[i+j]=1;
						innerSolve(i+1,0,n,num+1);	//递归求解
						frows[i]=0;
						fcols[j]=0;
						frowcol[i-j+n-1]=0;
						fcolrow[i+j]=0;
						board[i][j]='.';
					}
				}
			}
		}
	}
	vector<vector<string> > solveNQueens(int n) {
        ans.clear();	//初始化
		board.clear();
		frows.clear();
		fcols.clear();
		frowcol.clear();
		fcolrow.clear();
		string s;
		int i;
		for(i=0;i<n;i++)
		{
			s.push_back('.');
			frows.push_back(0);
			fcols.push_back(0);
		}
		for(i=0;i<2*n;i++)
		{
			frowcol.push_back(0);
			fcolrow.push_back(0);
		}
		for(i=0;i<n;i++)
			board.push_back(s);
		innerSolve(0,0,n,0);	//求解
		return ans;
    }
};


 

 

 

 

你可能感兴趣的:(LeetCode,C++,算法)