第一次写BFS自己的编译器都TLE..
  • 板块P1443 马的遍历
  • 楼主canwen
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/4/13 20:51
  • 上次更新2024/4/13 22:07:32
查看原帖
第一次写BFS自己的编译器都TLE..
1284815
canwen楼主2024/4/13 20:51
#include<bits/stdc++.h>
using namespace std;
typedef struct xy point;
struct xy{
    int x;
    int y;
};
queue <point> q;
int main(){
    int n,m,x0,y0;int ans[500][500];
    int dx[8]={-1,-2,-2,-1,1,2,1,2};
    int dy[8]={-2,-1,1,2,2,1,-1,-2};
    
    cin>>n>>m>>x0>>y0;
    memset(ans,-1,sizeof(ans));
    ans[x0][y0]=0;
    point p={x0,y0};
    q.push(p);
    while(!q.empty()){
        point tp;
        tp=q.front();//取队首 (x,y) 
        for(int i=0;i<8;i++){
            int xx=tp.x+dx[i];
            int yy=tp.y+dy[i];
            if(xx<1||yy<1||xx>n||yy>m||ans[xx][yy]!=-1) continue;
            //压栈
            ans[xx][yy]=ans[tp.x][tp.y]+1;
            point xxx={xx,yy};
            q.push(xxx);
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cout<<ans[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

2024/4/13 20:51
加载中...