博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
洛谷 1443——马的遍历(广度优先搜索)
阅读量:4549 次
发布时间:2019-06-08

本文共 1735 字,大约阅读时间需要 5 分钟。

题目描述

有一个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学的好的人完全不是问题,用头指针head和尾指针tail来记录当前搜到那个点head,将这个点存在tail的位置。

向八个方向搜,如果这个点没有被搜过(广搜如果搜到一定是最优解)和没有跳出范围。就将这个点存起来,最后输出最坑,要将长度补齐,不能只输出一个空格。


代码如下:

const dx:array[1..8]of longint=(1,1,-1,-1,2,2,-2,-2);      dy:array[1..8]of longint=(2,-2,2,-2,1,-1,-1,1);var   n,m,qx,qy,i,j:longint;      s:string;      a:array[-10..502,-10..502]of longint;      f:array[-10..502,-10..502]of boolean;function pd(x,y:longint):boolean;begin  if (x<1)or(y<1)or(x>n)or(y>m) then exit(false);  if f[x,y]=false then exit(false);  exit(true);end;procedure bfs;var    head,tail,i:longint;       state:array[0..160001,1..2]of longint;       father:array[0..160001]of longint;begin  fillchar(state,sizeof(state),#0);  fillchar(father,sizeof(father),#0);  head:=0; state[1,1]:=qx; state[1,2]:=qy; tail:=1; father[1]:=0;  fillchar(f,sizeof(f),true);  f[qx,qy]:=false;  repeat    inc(head);    for i:=1 to 8 do      if pd(state[head,1]+dx[i],state[head,2]+dy[i])=true then        begin          inc(tail);          state[tail,1]:=state[head,1]+dx[i];          state[tail,2]:=state[head,2]+dy[i];          father[tail]:=father[head]+1;          a[state[tail,1],state[tail,2]]:=father[tail];          f[state[tail,1],state[tail,2]]:=false;        end;  until head>=tail;end;begin  read(n,m,qx,qy);  for i:=1 to n do    for j:=1 to m do a[i,j]:=-1;  a[qx,qy]:=0;  bfs;  for i:=1 to n do    begin      for j:=1 to m do        begin          str(a[i,j],s);          write(s,' ':5-length(s));        end;      writeln;    end;end.

转载于:https://www.cnblogs.com/Comfortable/p/8412440.html

你可能感兴趣的文章
wamp服务器
查看>>
Codeforces 1144G Two Merged Sequences dp
查看>>
STL内存分配方式
查看>>
NS2移动节点
查看>>
python学习之路(十一)
查看>>
CSS让浮动元素水平居中
查看>>
-----------------时间线分水岭--------------------------
查看>>
Stsadm.exe 怎么用?
查看>>
使用spring中4.2.6版本使用@Value取值失败,结果为${xxx}的情况
查看>>
LOJ6583 ICPC World Finals 2019何以伊名始(广义后缀自动机)
查看>>
lightoj 1031【区间DP,未完待续】
查看>>
11、求二进制中1的个数
查看>>
【nodejs】让nodejs像后端mvc框架(asp.net mvc)一样处理请求--请求处理结果适配篇(7/8)...
查看>>
CodeForces 731A Night at the Museum
查看>>
MySQL 删除数据库
查看>>
JavaScript 字符串(String) 对象
查看>>
How to use VisualSVN Server and TortoiseSVN to host your codes and control your codes' version
查看>>
微信小程序picker组件 - 省市二级联动
查看>>
Dynamics CRM 给视图配置安全角色
查看>>
Eclipse修改已存在的SVN地址
查看>>