最近写代码好少,手生得很,反思...
存个代码
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int R, C;
int ix, iy, tx, ty;
char mp[N][N];
bool vis[N][N];
bool mark1[N][N];
bool mark2[N][N];
// 上、右、下、左
int dir[][2] = {-1,0,0,1,1,0,0,-1};
bool check(int x, int y, int k) {
if (mp[x][y] == 'T' || mp[x][y] == 'S' || mp[x][y] == '+') return true;
if (mp[x][y] == '.' && k == 2) return true;
if (mp[x][y] == '-' && (k == 1 || k == 3)) return true;
if (mp[x][y] == '|' && (k == 0 || k == 2)) return true;
return false;
}
void dfs1(int x, int y) {
mark1[x][y] = true;
for (int i = 0; i < 4; i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (xx < 1 || xx > R || yy < 1 || yy > C) continue;
if (mark1[xx][yy] || mp[xx][yy] == '#')
continue;
if (check(x, y, i))
dfs1(xx, yy);
}
}
void dfs2(int x, int y) {
mark2[x][y] = true;
for (int i = 0; i < 4; i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (xx < 1 || xx > R || yy < 1 || yy > C) continue;
if (mark2[xx][yy] || mp[xx][yy] == '#')
continue;
if (check(xx, yy, i ^ 2))
dfs2(xx, yy);
}
}
int main() {
cin >> R >> C;
for (int i = 1; i <= R; i++) {
for (int j = 1; j <= C; j++) {
cin >> mp[i][j];
if (mp[i][j] == 'S') {
ix = i;
iy = j;
} else if (mp[i][j] == 'T') {
tx = i;
ty = j;
}
}
}
dfs1(ix, iy);
if (!mark1[tx][ty]) {
cout << "I'm stuck!\n";
} else {
dfs2(tx, ty);
int ans = 0;
for (int i = 1; i <= R; i++) {
for (int j = 1; j <= C; j++) {
if (mark1[i][j] && !mark2[i][j]) ans++;
}
}
cout << ans << '\n';
}
}