MLE+WA+AC
原题链接:8048.马的遍历2024-08-06 09:50:59
发布于:浙江
成分复杂,有没有大佬帮忙改改
#include<iostream>
#include<queue>
using namespace std;
struct node{
int x,y;
int step;
};
int m,n,x,y,dir[8][2]={{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}},vis[410][410];
int main(){
int m,n,x,y;
cin>>m>>n>>x>>y;
queue<node> q;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
q.push({x,y,0});
while(!q.empty()){
node t=q.front();
q.pop();
if(t.x==i&&t.y==j){
cout<<t.step<<" ";
break;
}
for(int i=0;i<=7;i++){
int nx=t.x+dir[i][0],ny=t.y+dir[i][1];
if(nx<=m&&nx>=1&&ny<=n&&ny>=1&&vis[nx][ny]!=1){
q.push({nx,ny,t.step++});
vis[nx][ny]=1;
}
}
}
}
cout<<"\n";
}
return 0;
}
全部评论 1
#include <iostream> #include <queue> using namespace std; int dist[401][401]; const int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2}; const int dy[] = {1, 2, 2, 1, -1, -2, -2, -1}; void bfs(int x, int y, int n, int m) { // 初始化 for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dist[i][j] = -1; } } dist[x][y] = 0; queue<pair<int, int>> q; q.push({x, y}); while (!q.empty()) { auto [cx, cy] = q.front(); q.pop(); for (int k = 0; k < 8; k++) { int nx = cx + dx[k], ny = cy + dy[k]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && dist[nx][ny] == -1) { dist[nx][ny] = dist[cx][cy] + 1; q.push({nx, ny}); } } } } int main() { int n, m, x, y; cin >> n >> m >> x >> y; bfs(x, y, n, m); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cout << dist[i][j] << " "; } cout << endl; } return 0; }
2024-08-11 来自 广东
0
有帮助,赞一个