POJ 3083 Children of the Candy Corn

DFS和BFS的综合应用。分别输出一个迷宫由起点开始,左手优先路径长度,右手优先路径长度,以及最短路径长度。其中,前两个采用dfs,而最后一个采用bfs。注意下标w, h不要搞混,好容易wa...另外,用(i + 3) % 4 和 (i + 1) % 4表示方向,也是参考了别人的代码才理解的,画个图,试几个例子就很好理解了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
char maze[45][45];
bool flag[45][45];
int w, h;
int cnt;
bool p;
struct node
{
	int x, y, step;
};
void dfsl(int x, int y, int i)
{
	if (p || maze[x][y] == 'E')
	{
		p = true;
		return;
	}
	int cx = x + dx[i];
	int cy = y + dy[i];
	while (cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#')
	{
		i = (i + 3) % 4;
		cx = x + dx[i];
		cy = y + dy[i];
	}
	cnt++;
	dfsl(cx, cy, (i + 1) % 4);
}
void dfsr(int x, int y, int i)
{
	if (p || maze[x][y] == 'E')
	{
		p = true;
		return;
	}
	int cx = x + dx[i];
	int cy = y + dy[i];
	while (cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#')
	{
		i = (i + 1) % 4;
		cx = x + dx[i];
		cy = y + dy[i];
	}
	cnt++;
	dfsr(cx, cy, (i + 3) % 4);
}
int bfs(int start_x, int start_y)
{
	queue<node> q;
	node start;
	start.x = start_x;
	start.y = start_y;
	start.step = 1;
	q.push(start);
	flag[start_x][start_y] = 1;
	while (!q.empty())
	{
		node n = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int cx = n.x + dx[i];
			int cy = n.y + dy[i];
			if (flag[cx][cy] || cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#')
				continue;
			start.x = cx;
			start.y = cy;
			start.step = n.step + 1;
			flag[cx][cy] = 1;
			if (maze[cx][cy] == 'E')
				return start.step;
			q.push(start);
		}
	}
}
int main()
{
	int t;
	int start_x, start_y;
	scanf("%d", &t);
	while (t--)
	{
		memset(flag, 0, sizeof(flag));
		scanf("%d%d", &w, &h);
		for (int i = 0; i < h; i++)
		{
			scanf("%s", &maze[i]);
			for (int j = 0; j < w; j++)
			{
				if (maze[i][j] == 'S')
				{
					start_x = i;
					start_y = j;
				}
			}
		}
		cnt = 1, p = false;
		dfsl(start_x, start_y, 0);
		printf("%d ", cnt);
		cnt = 1, p = false;
		dfsr(start_x, start_y, 0);
		printf("%d ", cnt);
		printf("%d\n", bfs(start_x, start_y));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值