BFS 60pts,TLE了

P1443 马的遍历

可以考虑在bfs的时候将最短步数记下,这样bfs一次就行
by Geoyster @ 2023-05-14 10:21:03


@[tiaotiao0830](/user/542893) 您的 $bfs$ 码风好奇怪 ```cpp #include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<queue> using namespace std; int n,m,bx,by,dis[410][410]; int b[8][2] = {{2,1},{1,2},{-2,1},{-1,2},{2,-1},{1,-2},{-2,-1},{-1,-2}}; void bfs(int bx,int by) { memset(dis,-1,sizeof(dis)); queue<int> qx,qy; qx.push(bx); qy.push(by); dis[bx][by] = 0; while(!qx.empty()) { int x = qx.front(),y = qy.front(); qx.pop(); qy.pop(); for(int i = 0;i <= 7;i++) { int nx = x + b[i][0],ny = y + b[i][1]; if (nx <= 0 || nx > n || ny <= 0 || ny > m) continue; if (dis[nx][ny] > -1) continue; dis[nx][ny] = dis[x][y] + 1; qx.push(nx); qy.push(ny); } } } int main() { cin >> n >> m; cin >> bx >> by; bfs(bx,by); for (int i = 1;i <= n;i++) { for (int j = 1;j <= m;j++) { printf("%5d",dis[i][j]); } cout << endl; } return 0; } ```
by codejiahui @ 2023-05-14 10:23:46


|