华为编程大赛--笨笨熊搬家

本文介绍了一种算法,用于在二维地图上寻找指定位置的房屋,并判断从起点到终点是否存在路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求:


代码实现如下:

#include <iostream>
#include <vector>
#include <string>

typedef struct Pos
{
	int x;
	int y;
} Pos;

bool findPosition(std::vector<std::string> map, Pos &B, Pos &H)
{	
	bool findB = false, findH = false;
	for (int i = 0; i < map.size(); i++)
	{
		for (int j = 0; j < map[i].size(); j++)
		{
			if (map[i][j] == 'B')
			{
				B.x = i;
				B.y = j;
				findB = true;
			}
			if (map[i][j] == 'H')
			{
				H.x = i;
				H.y = j;
				findH = true;
			}
			if (findB && findH)
			{
				return true;
			}
		}
	}
	return false;
}

bool findPath(std::vector<std::string> map, Pos B, Pos H)
{
	if (map.size() == 0)
	{
		return false;
	}
	int R = map.size();
	int C = map[0].size();
	Pos judgePos,temp;
	std::vector<Pos> allPosition;
	allPosition.push_back(B);
	while(!allPosition.empty())
	{
		judgePos = allPosition.back();
		if (judgePos.x == H.x && judgePos.y == H.y)
		{
			return true;
		}
		allPosition.pop_back();
		//上下左右四个方向移动
		int move[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
		for (int i = 0; i < 4; i++)
		{
			temp.x = judgePos.x + move[i][0];
			temp.y = judgePos.y + move[i][1];
			if (temp.x >= 0 && temp.x < R && temp.y >= 0 && temp.y < C)
			{
				if (temp.x == H.x && temp.y == H.y)
				{
					return true;
				}
				if (map[temp.x][temp.y] == '-')
				{
					allPosition.push_back(temp);
					map[temp.x][temp.y] = '#';
				}

			}
		}
	}
	return false;
}



int main()
{
	int R, C;
	Pos posB, posH;
	std::cin>>R>>C;
	std::vector<std::string> map;
	for (int i = 0; i < R; i++)
	{
		std::string temp;
		std::cin>>temp;
		map.push_back(temp);
	}

	//获取房子的坐标
	if(!findPosition(map,posB, posH))
	{
		std::cout<<'N';
	}

	//判断是否有路径
	if (findPath(map, posB, posH))
	{
		std::cout<<'Y';
	}
	else 
	{
		std::cout<<'N';
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值