BFS做法
#include <iostream>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int N = 55;
int R, C;
char s[N][N];
int su1, su2, de1, de2;
int visited[N][N];
vector<pair<int, int>> v;
int x1[4] = {0, 1, -1, 0}, y1[4] = {1, 0, 0, -1};
int x3[2] = {1, -1};
int bfs(int x, int y) {
queue<pair<int, int>> q;
int flagt = 0;
memset(visited, 0, sizeof visited);
visited[x][y] = 1;
q.push({x, y});
while (!q.empty()) {
int s1 = q.front().first, s2 = q.front().second;
if (s[s1][s2] == 'T') {
flagt = 1;
if (s[x][y] != 'S') {
break;
}
}
if ( s[x][y] == 'S' && s[s1][s2] != 'S') {
v.push_back({s1, s2});
}
//else if (s[x][y] != 'S' && s[s1][s2] == 'S') {
// flagt = 1;
// break;
//}
q.pop();
char dir = s[s1][s2];
// // // //
if (dir == 'S' || dir == 'T' || dir == '+') {
for (int i = 0; i < 4; i++) {
int s3 = s1 + x1[i], s4 = s2 + y1[i];
if (!visited[s3][s4] && s[s3][s4] != '#') {
visited[s3][s4] = 1;
q.push({s3, s4});
}
}
} else if (dir == '-') {
for (int i = 0; i < 2; i++) {
int s3 = s1, s4 = s2 + x3[i];
if (!visited[s3][s4] && s[s3][s4] != '#') {
visited[s3][s4] = 1;
q.push({s3, s4});
}
}
} else if (dir == '|') {
for (int i = 0; i < 2; i++) {
int s3 = s1 + x3[i], s4 = s2;
if (!visited[s3][s4] && s[s3][s4] != '#') {
visited[s3][s4] = 1;
q.push({s3, s4});
}
}
} else if (dir == '.') {
int s3 = s1 + 1, s4 = s2 ;
if (!visited[s3][s4] && s[s3][s4] != '#') {
visited[s3][s4] = 1;
q.push({s3, s4});
}
}
}
return flagt;
}
int main() {
int res = 0;
cin >> R >> C;
for (int i = 0; i <= R + 1; i++) {
s[i][0] = '#';
s[i][C + 1] = '#';
}
for (int i = 0; i <= C + 1; i++) {
s[0][i] = '#';
s[R + 1][i] = '#';
}
for (int i = 1; i <= R; i++)
for (int j = 1; j <= C; j++) {
cin >> s[i][j];
if (s[i][j] == 'S')
su1 = i, su2 = j;
if (s[i][j] == 'T')
de1 = i, de2 = j;
}
int flag = bfs(su1, su2);
//for (int i = 1; i <= R; i++)
// for (int j = 1; j <= C; j++) {
// cout << s[i][j] << " ";
// if (j == C)
// cout << endl;
// }
if (flag == 0) {
cout << "I'm stuck!" << endl;
return 0;
}
for (int i = 0; i < v.size(); i++) {
if (!bfs(v[i].first, v[i].second))
res++;
}
cout << res << endl;
return 0;
}