BFS,9TLE+1AC

P1746 离开中山路

```cpp #include <iostream> #include <queue> using namespace std; const int N = 1050; int n, sx, sy, fx, fy, vis[N][N]; const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; char a[N][N]; int bfs(int posx, int posy) { queue <pair<pair<int, int>, int> > q; q.push(make_pair(make_pair(posx, posy), 0)); while(!q.empty()) { int x = q.front().first.first, y = q.front().first.second, round = q.front().second; q.pop(); vis[x][y] = 1; for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(nx < 1 || ny < 1 || nx > n || ny > n || vis[nx][ny] || a[nx][ny] == '1') continue; if(nx == fx && ny == fy) return round + 1; q.push(make_pair(make_pair(nx, ny), round + 1)); } } return -1; } int main() { cin >> n; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> a[i][j]; cin >> sx >> sy >> fx >> fy; cout << bfs(sx, sy) << endl; return 0; } ``` 第 $28$ 行的 `return -1;` 是为了函数严谨,会终止并返回错误值,但是问题肯定不在这里。
by 159号程序员 @ 2022-01-18 13:56:10


@[159号程序员](/user/334586) 如果出队的时候标记,那么就可能会导致同一个东西多次入队,应该是这里错了
by fjy666 @ 2022-01-18 13:59:38


@[fjy666](/user/366338) 把 `vis` 标记移到循环里?
by 159号程序员 @ 2022-01-18 14:00:44


@[159号程序员](/user/334586) [Here.你是不是错了细节第二条?](https://www.luogu.com.cn/blog/Cube-Dasher/solution-p4328)
by Argon_Cube @ 2022-01-18 14:02:20


@[159号程序员](/user/334586) 就是在进队的时候 vis[x][y]=1 就行了qwq
by fjy666 @ 2022-01-18 14:03:23


@[Epsilon_Cube](/user/372983) 大概率是,我调一下看看
by 159号程序员 @ 2022-01-18 14:03:47


@[fjy666](/user/366338) 我试试看
by 159号程序员 @ 2022-01-18 14:04:04


```diff while(!q.empty()) { int x = q.front().first.first, y = q.front().first.second, round = q.front().second; q.pop(); + if (vis[x][y]) continue; vis[x][y] = 1; for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; - if(nx < 1 || ny < 1 || nx > n || ny > n || vis[nx][ny] || a[nx][ny] == '1') continue; + if(nx < 1 || ny < 1 || nx > n || ny > n || a[nx][ny] == '1') continue; if(nx == fx && ny == fy) return round + 1; q.push(make_pair(make_pair(nx, ny), round + 1)); } } ```
by ud2_ @ 2022-01-18 14:04:17


@[ud2_](/user/206953) 理解
by 159号程序员 @ 2022-01-18 14:05:39


@[fjy666](/user/366338) @[ud2_](/user/206953) @[Epsilon_Cube](/user/372983) 感谢各位,AC了/qq
by 159号程序员 @ 2022-01-18 14:18:16


|