C - Children of the Candy Corn

C - Children of the Candy Corn

 
src="https://vjudge.net/problem/description/8026?1515639480000" width="100%" height="1531px" frameborder="0" scrolling="no" style="box-sizing: inherit;">
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char map[45][45];
int h, w, cnt, book[45][45], flag;
int dir[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
struct node{
	int x, y, step;
}a, b;

void dfs(int x, int y, int ex, int ey, int d)
{
	int i, j, tx, ty;
	if(x==ex && y==ey)
	{
		flag=1;
		printf("%d ", cnt);
		return ;
	}
	d=(d+3)%4;
	for(i=d;i<d+4;i++)
	{
		tx=x+dir[i%4][0];
		ty=y+dir[i%4][1];
		if(tx<0 || tx>=h || ty<0 || ty>=w)
			continue;
		if(map[tx][ty]!='#')
		{
			cnt++;
			d=i;
			dfs(tx, ty, ex, ey, d);
			if(flag)
				return ;
		}
	}
}

void bfs(int sx, int sy, int ex, int ey)
{
	queue<node>q;
	a.x=sx;	a.y=sy;	a.step=1;
	q.push(a);
	while(!q.empty())
	{
		a=q.front(); q.pop();
		if(a.x==ex && a.y==ey)
		{
			printf("%d\n", a.step);
			return ;
		}
		for(int i=0;i<4;i++)
		{
			b.x=a.x+dir[i][0];
			b.y=a.y+dir[i][1];	
			b.step=a.step+1;
			if(b.x>=0 && b.x<h && b.y>=0 && b.y<w && map[b.x][b.y]!='#' && !book[b.x][b.y])
			{
				book[b.x][b.y]=1;
				q.push(b);
			}
			
		}
	}
}

int main()
{
	int n, i, j, sx, sy, ex, ey;
	scanf("%d", &n);
	while(n--)
	{
		memset(book, 0, sizeof(book));
		scanf("%d%d", &w, &h);
		for(i=0;i<h;i++)
		{
			getchar();
			for(j=0;j<w;j++)
			{
				scanf("%c", &map[i][j]);
				if(map[i][j]=='S')
				{
					sx=i;
					sy=j;
				} 
				if(map[i][j]=='E')
				{
					ex=i;
					ey=j;
				}
			}
		}
		cnt=1;	flag=0;
		dfs(sx, sy, ex, ey, 0);
		cnt=1;	flag=0;
		dfs(ex, ey, sx, sy, 0);
		bfs(sx, sy, ex, ey);
	}
	return 0;
}
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hhjian6666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值