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.

《LeetCode | N-Queens》

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

思路:

非常典型的NP问题,利用递归回溯来解决放与不放的问题。

代码:

class Solution {
public:
    vector<string> str;
    vector<bool> rowConflict;
    vector<vector<string>> v;
    vector<vector<string>> solveNQueens(int n) {
    
    for(int i=0;i<n;i++)
    {
        string tmp;
        for(int i=0;i<n;i++)
        {
        	tmp.push_back('.');
        }
    	str.push_back(tmp);
    }
    
    for(int i=0;i<n;i++)
    {
    	rowConflict.push_back(false);
    }

    addAQueen(0, n);
    return v;

}

bool isConflict(int i, int j,int n)
{
	for(int k=1;k<n;k++)
	{
		if(str[(i+k)%n][(j+k)%n] == 'Q')
		{
		    if((i+k)%n-i==(j+k)%n-j)
			    return true;
        }
	}
	for(int k=1;k<n;k++)
	{
		if(str[(i+k)%n][(j-k+n)%n] == 'Q')
		{
		    if((i+k)%n-i==j-(j-k+n)%n)
			    return true;
        }
	}
	return false;
}

void addAQueen(int i, int n)
{
    if(i == n)
    {
        v.push_back(str);
        return;
    }
	for(int j=0;j<n;j++)
	{
		if(!rowConflict[j])
		{
			if(!isConflict(i,j,n))
			{
				str[i][j] = 'Q';
				rowConflict[j] = true;
				addAQueen(i+1,n);
                str[i][j] = '.';
                rowConflict[j] = false; 
			}
		}
	}
}
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17243057
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞