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
#include
#include
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;i4;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)
{
	queueq;
	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=0 && b.ymap[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;ifor(j=0;jscanf("%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;
}

你可能感兴趣的:(***ACM***搜索***)