zoukankan      html  css  js  c++  java
  • 马的遍历 new

    1【问题】

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

    【输入格式】

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

    【输出格式】

    一个n*m的矩阵,代表马到达某个点最少要走几步(中间的数用空格分开)

    【输入样例】

    3 3 1 1

    【输出样例】

    0 3 2
    3 -1 1
    2 1 4

     棋盘示意图:

    路线示意图:

    2【程序及备注】

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int N=401;//常量,最大401,数组从1开始,初始401 
     4 //马八个方向相对位置坐标 
     5 int pots[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
     6 int vis[N][N];//二维表坐标是否被访问过 
     7 int steps[N][N];//走到此位置需要的步数 
     8 int n,m,sx,sy;
     9 struct node{//坐标结构体 
    10     int x,y;
    11 };
    12 node pre,nex;
    13 
    14 //x,y坐标,s走到此位置需要的步数 
    15 void bfs(int x,int y,int s){ 
    16     queue<node> q;//队列,顺序存放每个位置 
    17     pre.x = x;
    18     pre.y = y;
    19     steps[x][y]=s;
    20     vis[x][y]=1;
    21     q.push(pre);//队列放入第一个坐标节点 
    22     while(!q.empty()){//队列有则取出 
    23         nex=q.front();
    24         q.pop();
    25         for(int i=0;i<8;i++){//逐一取出下一层8个节点 
    26             int xx=nex.x + pots[i][0];
    27             int yy=nex.y + pots[i][1];
    28             if(xx<=0 || xx>n || yy<=0 || yy>m){//越界重新for循环 
    29                 continue;
    30             }
    31             if(vis[xx][yy]!=1){//没访问过放入队列,计算步数 
    32                 vis[xx][yy]=1;
    33                 pre.x = xx;
    34                 pre.y = yy;
    35                 q.push(pre);
    36                 steps[xx][yy]=steps[nex.x][nex.y] + 1;
    37             }
    38         }
    39     }    
    40 }
    41 
    42 int main(){
    43     memset(steps,-1,sizeof(steps));//步数初始-1 
    44     memset(vis,0,sizeof(vis));//是否访问初始0 
    45     cin>>n>>m>>sx>>sy;
    46     bfs(sx,sy,0);//广度优先处理,填写对应最小步数 
    47     for(int i=1;i<=n;i++)
    48     {
    49         for(int j=1;j<=m;j++)
    50         {
    51             printf("%d ",steps[i][j]);
    52         }
    53         printf("\n");
    54     }
    55 } 
  • 相关阅读:
    框架比较
    框架整理
    bootstrap-table中get请求携带的参数
    0514任务思路
    两台电脑对码云上面的项目进行迭代
    项目问题
    vue 中发送axios请求,解决跨域问题(没有config文件)
    正则表达式(未完待续)
    【转载】深入理解Linux文件系统
    浅谈IO优化
  • 原文地址:https://www.cnblogs.com/myeln/p/13274172.html
Copyright © 2011-2022 走看看