C++#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// 方向数组:上、右、下、左
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
// BFS函数,计算从起点到目标字符的最短距离
int bfs(const vector<string>& grid, int start_x, int start_y, char target, int n, int k) {
// 初始化距离数组为无穷大
vector<vector<int>> dist(n, vector<int>(k, INT_MAX));
// 队列用于BFS
queue<pair<int, int>> q;
// 设置起点距离为0并加入队列
dist[start_x][start_y] = 0;
q.push({start_x, start_y});
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
// 如果找到目标,返回当前距离
if (grid[x][y] == target) {
return dist[x][y];
}
// 探索四个方向
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
// 检查新位置是否有效:在网格范围内,不是墙,且未访问过
if (nx >= 0 && nx < n && ny >= 0 && ny < k &&
grid[nx][ny] != '*' && dist[nx][ny] == INT_MAX) {
dist[nx][ny] = dist[x][y] + 1;
q.push({nx, ny});
}
}
}
// 如果无法到达目标(题目保证有解,此情况理论上不会发生)
return INT_MAX;
}
int main() {
int n, k;
cin >> n >> k;
vector<string> grid(n);
int start_x, start_y;
// 读取网格并找到小明的初始位置
for (int i = 0; i < n; ++i) {
cin >> grid[i];
for (int j = 0; j < k; ++j) {
if (grid[i][j] == '&') {
start_x = i;
start_y = j;
}
}
}
// 计算到两个房子的距离
int dist_percent = bfs(grid, start_x, start_y, '%', n, k);
int dist_hash = bfs(grid, start_x, start_y, '#', n, k);
// 比较距离并输出结果
if (dist_percent < dist_hash) {
cout << "%" << dist_percent << endl;
} else {
cout << "#" << dist_hash << endl;
}
return 0;
}