马的遍历(1443)

 

有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步

 

输入格式

 

一行四个数据,棋盘的大小和马的坐标

 

输出格式

 

一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

 

输入输出样例

 

输入 #1
3 3 1 1
输出 #1
0    3    2    
3    -1   1    
2    1    4    

 

 

 

``` #include #include #include #include using namespace std; int n,m; struct nds{     int x,y; }; queue q; int walk[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}}; int ans[405][405];//记录答案 void bfs(){     while (!q.empty()) //bfs模板(前提是:此时队列中已经推入了首结点)     {         nds u=q.front();         int ux=u.x;int uy=u.y;         q.pop();         for(int i=0;i<8;i++){       //第二层循环             int x=ux+walk[i][0];             int y=uy+walk[i][1];             int d=ans[ux][uy];  //每一次基于上一个节点重新计算距离             if(x<1||x>n||y<1||y>m||ans[x][y]!=-1){                 continue;   //越界则无需入队             }             ans[x][y]=d+1;//上一个节点扩展出来的点的距离:+1             nds tpp={x,y};             q.push(tpp);                     }     } } int main(){     int sx, sy;     memset(ans,-1,sizeof(ans));//cstring;     cin>>n>>m>>sx>>sy;     nds tmp = {sx, sy};     q.push(tmp);//先推入首结点,之后开始bfs     ans[sx][sy]=0;//到达首节点的距离为0     bfs();     for(int i=0;i<n;i++){         for(int j=0;j<m;j++){             printf("%-5d",ans[i][j]);         }         cout<<endl;     }     system("pause");   //cstdio } ```

 

posted @ 2021-02-23 20:19  py佐料  阅读(100)  评论(0)    收藏  举报