社区讨论
BFS20分求解 找不出问题
P1443马的遍历参与者 2已保存回复 3
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 3 条
- 当前快照
- 1 份
- 快照标识符
- @mi7djw56
- 此快照首次捕获于
- 2025/11/20 19:55 4 个月前
- 此快照最后确认于
- 2025/11/20 19:55 4 个月前
CPP
#include<iostream>
#include<cstring>
using namespace std;
int n,m,x,y,ans[405][405],t[400000][3];
int mx[8]={-2,-1,1,2,-2,-1,1,2},my[8]={-1,-2,-2,-1,1,2,2,1};
bool pd[405][405];
void bfs()
{
int head=1,tail=2;//指针设定
ans[x][y]=0;
pd[x][y]=1;
t[head][0]=x;//记录节点x
t[head][1]=y;//记录节点y
t[head][2]=0;//记录路径长度
while (head<tail)
{
for (int i=0;i<9;i++){
int xx=t[head][0]+mx[i],yy=t[head][1]+my[i];//八个方向搜索一遍
if (xx>=1&&xx<=n&&yy>=1&&yy<=m&&!pd[xx][yy]){
t[tail][0]=xx;
t[tail][1]=yy;
t[tail][2]=t[head][2]+1;//记录当前路径 长度
// cout<<xx<<" "<<yy<<" "<<t[tail][2]<<endl;
if (ans[xx][yy]<0) ans[xx][yy]=t[tail][2];//防止多次被遍历到而非最短路径
pd[xx][yy]=1;
tail++;
}
}
head++;
}
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++)
cout<<ans[i][j]<<" ";
cout<<endl;
}
}
int main()
{
memset(ans,-1,sizeof(ans));
cin>>n>>m>>x>>y;
bfs();
return 0;
}
回复
共 3 条回复,欢迎继续交流。
正在加载回复...