zoukankan      html  css  js  c++  java
  • 洛谷 P1443 马的遍历

    P1443 马的遍历

    题目描述

    有一个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<queue>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int n,m,tx,ty;
    int ans[410][410],vis[410][410];
    int dx[8]={1,1,-1,-1,2,-2,2,-2};
    int dy[8]={2,-2,2,-2,1,-1,-1,1};
    struct nond{
        int x,y,pos;
    };
    int main(){
        scanf("%d%d%d%d",&n,&m,&tx,&ty);
        nond tmp;vis[tx][ty]=1;
        tmp.x=tx;tmp.y=ty;tmp.pos=0;
        queue<nond>que;
        que.push(tmp);
        while(!que.empty()){
            nond now=que.front();
            que.pop();
            for(int i=0;i<8;i++){
                nond c;
                c.x=dx[i]+now.x;
                c.y=dy[i]+now.y;
                c.pos=now.pos+1;
                if(c.x>=1&&c.x<=n&&c.y>=1&&c.y<=m&&!vis[c.x][c.y]){
                    ans[c.x][c.y]=c.pos;vis[c.x][c.y]=1;
                    que.push(c);
                }
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(!vis[i][j])    ans[i][j]=-1;
                printf("%-5d",ans[i][j]);
            }
            cout<<endl;
        }    
    }
    细雨斜风作晓寒。淡烟疏柳媚晴滩。入淮清洛渐漫漫。 雪沫乳花浮午盏,蓼茸蒿笋试春盘。人间有味是清欢。
  • 相关阅读:
    input 去除边框
    分页封装
    python后端继承序列化,不同访问形式返回不同结果
    解决vue前端不显示自定义字段
    Vue 获取后端多对多关联表信息
    vue 前段增删改查代码规范
    前段增删改查的应用
    ant-design-vue基础
    python 后端 数据库的创表及增删改查 简单使用
    配置Uwsgi+Nginx+Django+Vue
  • 原文地址:https://www.cnblogs.com/cangT-Tlan/p/8045915.html
Copyright © 2011-2022 走看看