版本比较
3.8 bfs-1
正文
增加 15 行删除 15 行
34 行未改动35363738394039404142434445454647484950484950515253535455565755565758596061616263646565666768696869707172727374757614 行未改动34 行未改动
const int N = 45;
struct P { int x, y, st; // 这个点的行、列、步数 }; int x, y, st; // 这个点的行、列、步数};
int n, m;int d[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};int vis[N][N];char mp[N][N]; char mp[N][N];
void bfs() { memset(vis, 0, sizeof vis); // 清空标记 queue<P> q; // 结构体队列 memset(vis, 0, sizeof vis); // 清空标记 queue<P> q; // 结构体队列
q.push({1, 1, 1}); vis[1][1] = 1;
while (q.size()) { P now = q.front(); // 取出队首元素 q.pop(); P now = q.front(); // 取出队首元素 q.pop();
if (now.x == n and now.y == m) { cout << now.st; return ; } } for (int i=0; i<4; i++) { int nx = now.x + d[i][0]; int ny = now.y + d[i][1];
if (nx < 1 or nx > n or ny < 1 or ny > m) continue; if (mp[nx][ny] == '#' or vis[nx][ny]) continue; q.push({nx, ny, now.st+1}); // 新的点入队,并且表示当前点已经处理过
q.push({nx, ny, now.st+1}); // 新的点入队,并且表示当前点已经处理过 vis[nx][ny] = 1; } } }}
int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);14 行未改动