当前位置:网站首页>Blue Bridge Cup Square filling (DFS backtracking)

Blue Bridge Cup Square filling (DFS backtracking)

2022-07-05 01:16:00 Woodenman Du

Question:

 

Solve:

In general, it is a little Limited dfs Board question

Keep trying which number can be filled in each grid , Then go to the next box and continue filling , until 10 Put all the numbers in or you can't put them to an end

As for adjacent numbers , It can be written directly as enumeration if,CV Just modify it , Therefore, when I write code, I expand the range of coordinate grids , Then each cell is initialized directly to an impossible number

The second is to remember to look back after entering the next box

Code:

#include<bits/stdc++.h>
using namespace std;
int res = 0;	// Count  
int a[5][6];	// grid  
bool num[10];	// Numeric fill marks 
// Absolute value judgment  
int f(int x)
{
	return x < 0 ? -x : x;	
}
// Deep search  
void dfs(int x,int y,int deep)
{
	if(deep > 10){
		res++;
		return ;
	}
	for(int i = 0; i <= 9; i++){
		// The number is selected  
		if(num[i]) continue;
		// Cross lattice  
		if( f(a[x-1][y] - i)<=1 ) continue;
		if( f(a[x+1][y] - i)<=1 ) continue;
		if( f(a[x][y+1] - i)<=1 ) continue;A
		if( f(a[x][y-1] - i)<=1 ) continue;
		// Diagonally  
		if( f(a[x+1][y+1] - i)<=1 ) continue;
		if( f(a[x-1][y+1] - i)<=1 ) continue;
		if( f(a[x+1][y-1] - i)<=1 ) continue;
		if( f(a[x-1][y-1] - i)<=1 ) continue;
		// Fill in the figures , Go to the next level  
		a[x][y] = i; num[i] = true;
		if(x == 1 && y == 4) dfs(2,1,deep+1);
		else if(x == 2 && y == 4) dfs(3,1,deep+1);
		else dfs(x,y+1,deep+1);
		// to flash back  
		a[x][y] = -10; num[i] = false;
	}
}

int main(void)
{
	// initialization  
	memset(num,false,sizeof(num));
	for(int i = 0; i <= 4; i++)
	for(int j = 0; j <= 5; j++)
		a[i][j] = -10;
	// Search for  
	dfs(1,2,1);
	cout <<res;
	return 0;
}

Statement : The pictures are from the official website of the Blue Bridge Cup , For the purpose of sorting out personal questions , In case of infringement , Please contact to delete ~

原网站

版权声明
本文为[Woodenman Du]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141038416861.html

随机推荐