zoukankan      html  css  js  c++  java
  • 马的遍历(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 } ```

    这篇文章,是又一个故事的结束...
    lazy's story is continuing.
  • 相关阅读:
    算法15 《啊哈算法》第四章 盒子装扑克-DFS深度优先搜索 递归
    算法14 leetcode28 实现 strStr() kmp
    markdown一些有用笔记
    算法11 leetcode274 有效的字母异位词
    Quantity? Quality!
    算法 10 leetcode344. 反转字符串
    JavaWeb —— JDBC Driver驱动及连接问题
    Python —— 4 习题练习
    Python —— 变量的作用域
    JavaWeb —— 文件上传
  • 原文地址:https://www.cnblogs.com/Hello-world-hello-lazy/p/14437960.html
Copyright © 2011-2022 走看看