ZZUOJ 2n Queen Problem (DFS)

2n queen problem

Time limit: 1 Sec Memory limit: 128 MB

Problem description
Given a n*n chessboard, there are some positions on the chessboard that cannot be placed with queens. Now we need to put n black queens and n white queens into the chessboard, so that any two black queens are not in the same row, column or diagonal, and any two white queens are not in the same row, The same column or the same diagonal. How many ways are there in total? n is less than or equal to 8.

Input
The first line of input is an integer n, which represents the size of the chessboard.
In the next n lines, there are n integers of 0 or 1 in each line. If an integer is 1, it means that the corresponding position can be a queen. If an integer is 0, it means that the corresponding position cannot be a queen.

Output
Output an integer, indicating how many ways there are in total.

Sample input
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

Sample output
2

analysis:

In each search, two operations are performed on the board, "coloring (2)" and "branding (0)". The coloring means that this chess cannot be played, but the chess of other colors can be lowered, and the branding is not available for any chess. Down again.

Code:

#include <stdio.h>
using namespace std;
int N;
int dfs(int(*board)[10], int, int, int);//chessboard-row-column-order of arrange
int main()
{
    
    
	int board[10][10] = {
    
     0 }, sum = 0;//棋盘中 0不能放任何棋 1能放任何棋 2暂时不能放棋
	scanf("%d", &N);
	for (int i = 1; i <= N; i++)
	{
    
    
		for (int j = 1; j <= N; j++)
		{
    
    
			scanf("%d", &board[i][j]);
		}
	}
	for (int i = 1; i <= N; i++)
	{
    
    
		if (board[1][i] == 1)sum += dfs(board, 1, i, 1);
	}
	printf("%d", sum);
	return 0;
}
int dfs(int board[10][10], int r, int c, int order)
{
    
    
	int fboard[10][10], sum = 0;
	for (int i = 0; i<10; i++)
	{
    
    
		for (int j = 0; j<10; j++)
		{
    
    
			fboard[i][j] = board[i][j];
		}
	}
	fboard[r][c] = 0;//can't use this position ever
	if (r == N)
	{
    
    
		if (order == 2)
		{
    
    
			return 1;
		}
		else
		{
    
    
			for (int i = 1; i <= N; i++)
			{
    
    
				if (fboard[1][i] == 2)sum += dfs(fboard, 1, i, 2);
			}
		}
	}
	else
	{
    
    
		//coloring
		for (int i = r; i <= N; i++)
		{
    
    
			for (int j = 1; j <= N; j++)
			{
    
    
				if (fboard[i][j] && (i == r || j == c || i - r == j - c || i - r == c - j))fboard[i][j] = order + 1;
			}
		}
		//colored
		for (int i = 1; i <= N; i++)
		{
    
    
			if (fboard[r + 1][i] == order)
			{
    
    
				sum += dfs(fboard, r + 1, i, order);
			}
		}
	}
	return sum;
}

Guess you like

Origin blog.csdn.net/qq_43700916/article/details/88364573