如果你bfs MLE

P1189 SEARCH

就能大大优化空间 ```cpp #include <bits/stdc++.h> using namespace std; const int N = 50 + 5 , Q = 1e3 + 5 ; int n , m , qus , sx , sy ; char mp[N][N] ; int dx[Q] , dy[Q] , flag[N][N][Q] ; struct node { int x , y , num ; }; queue <node> q ; void bfs() { q.push({sx , sy , 0}) ; while(! q.empty() ) { node u = q.front() , v ; if(u.num == qus) break ; q.pop() ; for(int i = 1 ; ; i ++) { v.num = u.num + 1 ; v.x = u.x + dx[v.num] * i ; v.y = u.y + dy[v.num] * i ; if(v.x < 1 || v.x > n || v.y < 1 || v.y > m) break ; if(mp[v.x][v.y] == 'X') break ; if(flag[v.x][v.y][v.num] == 1) break ; flag[v.x][v.y][v.num] = 1 ; q.push({v.x , v.y , v.num}) ; } } return ; } int main() { cin >> n >> m ; for(int i = 1 ; i <= n ; i ++) { for(int j = 1 ; j <= m ; j ++) { cin >> mp[i][j] ; if(mp[i][j] == '*') sx = i , sy = j ; } } cin >> qus ; string s ; for(int i = 1 ; i <= qus ; i ++) { cin >> s ; if(s == "NORTH") dx[i] = -1 , dy[i] = 0 ; if(s == "SOUTH") dx[i] = 1 , dy[i] = 0 ; if(s == "WEST") dx[i] = 0 , dy[i] = -1 ; if(s == "EAST") dx[i] = 0 , dy[i] = 1 ; } bfs() ; mp[sx][sy] = '.' ; while(! q.empty() ) { node u = q.front() ; q.pop() ; mp[u.x][u.y] = '*' ; } for(int i = 1 ; i <= n ; i ++) cout << mp[i] + 1 << endl ; return 0; } ```
by Dream__maker @ 2024-02-22 17:25:15


对比[优化前](https://www.luogu.com.cn/record/148004361)和[优化后](https://www.luogu.com.cn/record/148005792)
by Dream__maker @ 2024-02-22 17:26:56


不过我这个做法好像空间大,效率还低 QwQ
by Dream__maker @ 2024-02-22 17:30:19


@[Dream__maker](/user/718017) 感谢,遇到了一模一样的问题,解决了。 仔细想想,其实就是遍历的时候会重复,导致程序效率低下,内存爆了。 ~~~~大家一定要应以为戒~~~~
by sll00 @ 2024-04-27 15:15:47


@[sll00](/user/1243869) 嗯加油,顺便壶关(doge
by Dream__maker @ 2024-04-27 15:16:52


@[Dream__maker](/user/718017) 当然
by sll00 @ 2024-04-27 15:42:32


|