题目要求:
代码实现如下:
#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;
}