剪枝点:
st数组 有点类似记忆化吧 用来记录到(i,j)这个点的最小步数
还有就是如果当前步数大于等于我们的ans(当前最小步数) 就返回
#include <bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int N = 105;
char mp[N][N];
int vis[N][N], st[N][N];
int dicx[5] = {0, -1, 1, 0, 0};
int dicy[5] = {0, 0, 0, -1, 1};
int sx, sy, ex, ey, r, c;
int ans = 0x3f3f3f3f;
void dfs(int x, int y, int step) {
if (step >= ans) return;
if (x == ex && y == ey) {
ans = min(ans, step);
return;
}
for (int i = 1; i <= 4; i++) {
int nx = x + dicx[i];
int ny = y + dicy[i];
if (nx >= 1 && nx <= r && ny >= 1 && ny <= c && !vis[nx][ny] && st[nx][ny] > st[x][y] + 1 && mp[nx][ny] != '#') {
vis[nx][ny] = 1;
st[nx][ny] = st[x][y] + 1;
dfs(nx, ny, step + 1);
vis[nx][ny] = 0;
}
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
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') {
sx = i;
sy = j;
}
if (mp[i][j] == 'T') {
ex = i;
ey = j;
}
}
}
memset(st, 0x3f, sizeof(st));
st[sx][sy] = 0;
vis[sx][sy] = 1;
dfs(sx, sy, 0);
cout << (ans == 0x3f3f3f3f ? -1 : ans) << endl;
return 0;
}
AC记录: