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

题目要求:


代码实现如下:

#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;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值