题目描述
​ 小明看完了电影,是时候回家了,可是这时他突然得知小米之家的小米9现货开卖了,这款手机小明已经想了一个多月,知道这个消息后的他十分兴奋,一定要在回家之前先去小米之家买手机(城市中有一个或多个小米之家),请计算小明从电影院到任意一个小米之家买手机后回家的最短距离(只能朝上下左右四个方向行走,除了障碍物外,其他地方都可以通过),数据保证可以买完手机后回家。

输入
​ 第 1 行两个数 n 和 m 表示地图有 n 行 m 列 2≤n,m≤2000​ 第 2 行至第 n+1 行为地图 其中 S 表示电影院 T 表示家 P 表示小米之家​ . 为可以通过的点 # 为障碍物

输出
​ 一个整数 表示小明从电影院去小米之家再回家的总距离

样例输入
5 5
.S…
###…
…T
.P##.
P…
样例输出
11

#include<iostream>
#include<queue>
using namespace std;

struct node {
int x, y, step,c;
};
int n, m, check[2005][2005], check2[2005][2005];
char map[2005][2005];
int dir[4][2] = { 0,1,1,0,0,-1,-1,0 };

int main() {
cin >> n >> m;
queue<node> que;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
if (map[i][j] == 'S') {
que.push({ i,j,0,0 });
check[i][j] = 1;
}
}
}
while (!que.empty()) {
node temp = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int x = temp.x + dir[i][0];
int y = temp.y + dir[i][1];
if (map[x][y] == 'T' && temp.c == 1) {
cout << temp.step + 1 << endl;
return 0;
}
if (map[x][y] == 'P' && check2[x][y] == 0) {
check2[x][y] = 1;
que.push({ x,y,temp.step + 1,1 });
}
else if (map[x][y] == '.' || map[x][y] == 'S' || map[x][y] == 'T') {
if (temp.c == 0 && check[x][y] == 0) {
check[x][y] = 1;
que.push({ x,y,temp.step + 1,0 });
}
else if (temp.c == 1 && check2[x][y] == 0) {
check2[x][y] = 1;
que.push({ x,y,temp.step + 1,1 });
}
}
}
}
return 0;
}
#include <iostream>
#include <queue>
using namespace std;

struct node {
int x, y, s, f;
};

int n, m, check[2005][2005];
char mmap[2005][2005];
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};

int main() {
queue<node> que;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> mmap[i][j];
if (mmap[i][j] == 'S') {
que.push({i, j, 0, 0});
check[i][j] = 1;
}
}
}
while (!que.empty()) {
node temp = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int x = temp.x + dir[i][0];
int y = temp.y + dir[i][1];
if (temp.f == 0 && check[x][y] & 1) continue;
if (temp.f == 1 && check[x][y] & 2) continue;
if (temp.f == 1 && mmap[x][y] == 'T') {
cout << temp.s + 1 << endl;
return 0;
}
if (mmap[x][y] == '.' || mmap[x][y] == 'S' || mmap[x][y] == 'T') {
que.push({x, y, temp.s + 1, temp.f});
check[x][y] += temp.f + 1;
}
if (mmap[x][y] == 'P') {
que.push({x, y, temp.s + 1, 1});
check[x][y] = 3;
}
}
}
return 0;
}