cf540C 搜索

题意:n*m的地图,'X'表示有裂痕的冰块,'.'表示完整的冰块,
有裂痕的冰块再被踩一次就会碎掉,完整的冰块被踩一次会变成有裂痕的冰块,
现在告诉起点和终点,问从起点能否走到终点并且使终点的冰块碎掉。不能原地跳。
起点和终点可能会在同一个位置。

思路1:bfs。从起点开始广搜,起点默认为X。
若碰到X,判断是否为终点。若是,结束算法,否则无法行走。
若碰到.,则变为X。

#include <cstdio>
#include <algorithm>
#include <queue>
#define N 505

using namespace std;

int n, m;
char map[N][N];
int sx, sy, ex, ey;

typedef struct note {
	int x; int y;
}point;

int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };

int isok(int x, int y)
{
	return x >= 0 && x < n && y >= 0 && y < m;
}

int bfs()
{
	queue<point> q;
	while (q.size())	q.pop();
	//初始化起点
	point s;
	s.x = sx; s.y = sy;
	q.push(s);
	map[s.x][s.y] = 'X';

	while (q.size())
	{
		point cur = q.front(); q.pop();//出队
		point t;
		for (int i = 0; i < 4; i++)//遍历4个方向
		{
			t.x = cur.x + dx[i]; t.y = cur.y + dy[i];
			if (!isok(t.x, t.y))//越界
				continue;
			if (map[t.x][t.y] == 'X')//到达X
			{
				if (t.x == ex && t.y == ey)//到达终点
					return 1;
				else//不可达
					continue;
			}
			if (map[t.x][t.y] == '.')//到达.
			{
				q.push(t);
				map[t.x][t.y] = 'X';
			}
		}
	}
	return 0;
}

int main()
{
	while (~scanf("%d%d", &n, &m))
	{
		for (int i = 0; i < n; i++)
			scanf("%s", map[i]);
		scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
		sx--; sy--; ex--; ey--;
		if (bfs())
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}

思路2:dfs。dfs一般用于判断是否能到达。此题正好适合,不过dfs在用于判断是否到达的问题时,
标记数组退栈时不用消除。(原因:若当前点不能到达,下次更不用搜索该点了)

#include <cstdio>
#include <algorithm>
#define N 505

using namespace std;

int n, m;
char map[N][N];
int sx, sy, ex, ey;
int flag = 0;

int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };

int isok(int x, int y)
{
	return x >= 0 && x < n && y >= 0 && y < m;
}

void dfs(int x, int y)
{
	for (int i = 0; i < 4; i++)
	{
		int tx = x + dx[i], ty = y + dy[i];
		if (!isok(tx, ty))
			continue;
		//对当前点分为终点和非终点两种情况
		if (tx == ex && ty == ey)
		{
			if (map[tx][ty] == 'X')
			{
				flag = 1;
				return;
			}
			else//终点是.
			{
				map[tx][ty] = 'X';
				dfs(tx, ty);
			}
		}
		else//非终点
		{
			if (map[tx][ty] == 'X')
				continue;
			else//是.
			{
				map[tx][ty] = 'X';
				dfs(tx, ty);
			}
		}
	}
}

int main()
{
	while (~scanf("%d%d", &n, &m))
	{
		for (int i = 0; i < n; i++)
			scanf("%s", map[i]);
		scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
		sx--; sy--; ex--; ey--;
		map[sx][sy] = 'X';
		dfs(sx, sy);
		if (flag)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值