HRBUST-1249-N queen problem

Title description:

N queens are placed on the N*N checkerboard, so that they do not attack each other (that is, any two queens are not allowed to be in the same row, the same column, and are not allowed to be on the diagonal line that is 45 angles to the border of the chessboard. .
your task is, for a given N, how many legitimate method of obtaining placed there.
the Input:
there are a number of lines, each a positive integer N≤10, represents the number of board and queen; if N = 0, represents End.
Output:
There are a number of rows, and each row has a positive integer, indicating the different placement quantities of the queen corresponding to the input row.


Ideas:

Seeing the title, it is obviously a DFS search. How to search? Here, N is N rows and N columns, N queens, any two queens are not allowed to be in the same row, the same column, nor are they allowed to be on a diagonal line that is 45 angles to the border of the chessboard. In this case, we can put the queen from the first line, and then put it line by line. When we put each line, we judge whether it can be put in a certain column. If so, we can put the queen in the next line, until the n+1th one ends the search. Look at the code below.


We use map[x] to represent this queen, and place it in the xth row and column map[x]. The check(x) function can be used to judge the queen when it can be placed in this row and this column. If it is possible, it will return 1. It returns 0.
It should be noted that here you need to hit the table first, otherwise it will time out.

int check(int x)//检查x行map[x]列是否可以放 
{
    
    
	for(int i=1;i<x;i++)
	{
    
    
		if(map[i]==map[x]||abs(x-i)==abs(map[x]-map[i]))//列相等或者对角线成45度,返回0 
			return 0;
	}
	return 1;
} 

Complete code:

#include <iostream>
#include <cmath>
using namespace std;
int n,sum,map[15],a[15];

int check(int x)//检查x行map[x]列是否可以放 
{
    
    
	for(int i=1;i<x;i++)
	{
    
    
		if(map[i]==map[x]||abs(x-i)==abs(map[x]-map[i]))//列相等或者对角线成45度,返回0 
			return 0;
	}
	return 1;
} 

void dfs(int x)//第x行 
{
    
    
	if(x>n)
	{
    
    
		sum++;
		return;
	}
	for(int i=1;i<=n;i++)
	{
    
    
		map[x]=i;
		if(check(x))//可以放 
			dfs(x+1);
	}
}

int main()
{
    
    
	for(int i=1;i<=10;i++)
	{
    
    
		sum=0;
		n=i;
		dfs(1);
		a[i]=sum;
	} 
	while(cin>>n&&n)
	{
    
    
		cout<<a[n]<<endl;
	}
	
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_45102820/article/details/113790740