题目描述

有一个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

思路:裸bfs,输出的时候比较坑是%-5d

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#include<cmath>
#include<list>
#define N 300005 typedef long long ll;
using namespace std;
int Map[405][405];
int vis[405][405];
int n,m,sx,sy;
struct node
{
int x, y;
int step; };
int dir[8][2]={{2,1},{1,2},{2,-1},{1,-2},{-2,1},{-1,2},{-1,-2},{-2,-1}};
void bfs(int x,int y)
{
queue<node>q;
node start;
start.x=x;
start.y=y;
start.step=0;
Map[x][y]=start.step;
q.push(start);
while(!q.empty())
{
node now=q.front();
q.pop();
for(int t=0;t<8;t++)
{
node next;
next.x=now.x+dir[t][0];
next.y=now.y+dir[t][1];
next.step=now.step+1;
if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&vis[next.x][next.y]==0)
{
q.push(next); vis[next.x][next.y]=1;
Map[next.x][next.y]=next.step;
}
}
}
}
int main()
{ cin>>n>>m>>sx>>sy;
vis[sx][sy]=1;
memset(Map,-1,sizeof(Map)); bfs(sx,sy);
for(int t=1;t<=n;t++)
{
for(int j=1;j<=m;j++)
{ printf("%-5d",Map[t][j]); }
cout<<endl;
}
return 0;
}

最新文章

  1. nginx配置之取消index.php同时不影响js,css功能
  2. Centos 6.5 rsync+inotify 两台服务器文件实时同步
  3. 获取win7时区所有信息
  4. Java Calendar获取年、月、日、时间
  5. ORACLE表空间bigfile和smallfile
  6. nginx构建https
  7. launchMode 和 onNewIntent 关系 任务栈知识.
  8. [原创]HBase学习笔记(3)- Java程序访问HBase
  9. 【网站管理3】_ftp连接超时和连不上的原因
  10. Sampling Distributions and Central Limit Theorem in R(转)
  11. PHP_保留两位小数并且四舍五入_保留两位小数并且不四舍五入
  12. Linux调整日期时间
  13. 在Ubuntu 18.04 安装 MySQL 8.0
  14. 数据库中id为自增
  15. Android IPC机制(三)使用AIDL实现跨进程方法调用
  16. ssm又乱码
  17. 个人小爱好:Operating System:three easy pieces---第6章第4节_担心并发问题?
  18. C#中关于DataGridView行和列的背景色-前景色设置
  19. appium 3-31626 toast识别
  20. 2018.10.23 hdu4745Two Rabbits(区间dp)

热门文章

  1. mybatis 框架 的应用之四(一对一 与 一对多)
  2. HighCharts SVN IReport进行PDF报表设计--模板
  3. 关于for循环的一个小问题
  4. c语言学习笔记 if语句的条件判断
  5. CF519E A and B and Lecture Rooms
  6. Install zlib/libpng/jpeg/freetype/libgd/GD on Mavericks即mac10.9(转)
  7. java实现wc功能
  8. HackNine 避免在EditText中验证日期
  9. Jmeter响应中文乱码解决办法
  10. Linux环境下mysql安装并配置远程访问