BFS,就是设计一个结构体这个思路比较好
#include <bits/stdc++.h>
using namespace std;
struct node {
int x, y, step, count;
node(int x_, int y_, int s_,
int c_) : x(x_), y(y_), step(s_), count(c_) {}
};
vector<vector<int>> dir = {{1, -1, 0, 0}, {0, 0, 1, -1}};
bool check(vector<vector<bool>>& vis, int x, int y) {
int n = vis.size(), m = vis[0].size();
if(x >= 0 && x < n && y >= 0 &&
y < m && !vis[x][y]) return 1;
return 0;
}
int main() {
int m, n;
int sx, sy, ex,ey, ans = 0;
scanf("%d%d", &n, &m);
vector<string> grid(n);
vector<vector<bool>> vis(n, vector<bool>(m, 0));
for(int i = 0; i < n; ++i) {
cin >> grid[i];
int y;
if((y = grid[i].find('S')) != -1) { sx = i; sy = y; }
if((y = grid[i].find('E')) != -1) { ex = i; ey = y; }
}
queue<node*> q;
q.push(new node(sx, sy, 0, 5));
vis[sx][sy] = 1;
bool flag = 0;
while(q.size()) {
node* top = q.front();
q.pop();
if(grid[top->x][top->y] == 'E') {
printf("%d\n", top->step);
flag = 1;
break;
}
int xx, yy;
for(int i = 0; i < 4; ++i) {
xx = top->x + dir[0][i]; yy = top->y + dir[1][i];
if(check(vis, xx, yy) && grid[xx][yy] != '#') {
vis[xx][yy] = 1;
q.push(new node(xx, yy, top->step + 1, top->count));
}
}
xx = n - 1 - top->x; yy = m - 1 - top->y;
if(top->count > 0 && check(vis, xx, yy) && grid[xx][yy] != '#') {
vis[xx][yy] = 1;
q.push(new node(xx, yy, top->step + 1, top->count - 1));
}
delete top;
}
if(!flag) printf("%d\n", -1);
}