2017 ACM QingDao The Squared Mosquito Coil

Lusrica designs a mosquito coil in a board with n × n grids. The mosquito coil is a series of consecutive grids, each two neighboring grids of which share a common border. If two grids in the mosquito coil are not consecutive, they do not share any border, but they can share a common endpoint.

The mosquito coil Lusrica designed starts from the upper left corner of the board. It goes right to the last available grid. Alter the direction and go downward to the last available grid, and alter the direction again going left to the last available grid. To carry on after altering the direction and go upward to the last available grid. Then it goes right again and repeats the above turns.

It ends up in a grid such that the above process cannot be continued any more. Your mission now is to print the whole blueprint of Lusrica's mosquito coil.

Input

This problem has several test cases and the first line contains an integer t (1 ≤ t ≤ 36) which is the number of test cases. For each case a line contains an integer n (1 ≤ n ≤ 36) indicating the size of the board.

Output

For each case with input n, output n lines to describe the whole board. Each line contains n characters. If a grid is a part of Lusrica's mosquito coil, the corresponding character is '#', or ' ' (a single blank) if not.

样例输入

5
1
2
3
4
5

样例输出

#
##
 #
###
  #
###
####
   #
#  #
####
#####
    #
### #
#   #
#####

青岛现场赛题

题目说是一盘蚊香 我觉得有点像贪吃蛇的意思 要碰到自己的时候就转弯

一个简单的dfs就可以啦

我这里考虑的都是内部转弯的情况 所以n<=3时都枚举了一遍

代码如下:

#include<iostream>
#include<cstring>
using namespace std;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int map[40][40];
void print(int n)
{
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(map[i][j]) cout<<'#';
			else cout<<' ';
		}
		cout<<endl;
	}
}
void dfs(int n,int x,int y,int d){
	map[x][y]=1;
	int dn=(d+1)%4;
	int xn=x+dir[dn][0];
	int yn=y+dir[dn][1];
	int count=0;
	if(x+dir[d][0]<=n&&x+dir[d][0]>=1&&y+dir[d][1]>=1&&y+dir[d][1]<=n)
	{
		for(int i=0;i<4;i++)
		{
			if(map[xn+dir[i][0]][yn+dir[i][1]]) count++;
		}
		if(map[x+dir[d][0]*2][y+dir[d][1]*2]&&count>=2)
		{
			print(n);
			return ;
		}
	}
	if(x+dir[d][0]>n||x+dir[d][0]<1||y+dir[d][1]>n||y+dir[d][1]<1)
	{
		dfs(n,xn,yn,dn);
		return ;
	}
	else if(map[x+dir[d][0]*2][y+dir[d][1]*2])
	{
		dfs(n,xn,yn,dn);
		return ;
	}
	else
	{
		dfs(n,x+dir[d][0],y+dir[d][1],d);
	}
	return ;
	
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		int n;
		cin>>n;
		memset(map,0,sizeof(map));
		if(n==1)
		{
			map[1][1]=1;
			print(n);
		}
		else if(n==2)
		{
			map[1][1]++;
			map[1][2]++;
			map[2][2]++;
			print(n);
		}
		else if(n==3)
		{
			map[1][1]++;
			map[1][2]++;
			map[1][3]++;
			map[2][3]++;
			map[3][3]++;
			map[3][2]++;
			map[3][1]++;
			print(n);
		}
		else
		{
			dfs(n,1,1,0);
		}
		
	}
} 

猜你喜欢

转载自blog.csdn.net/zyw764662004/article/details/81319947