洛谷 马的遍历
2017-07-03 11:41
190 查看
#include <cstdio>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
queue <int> qx; //定义横坐标队列
queue <int> qy; //定义纵坐标队列
int n,m,a[405][405]; //存放步数
int i,j,k,dx,dy,p,q;
const int dir[8][2]={ //状态转移数组==方向向量
{1,2},
{1,-2},
{-1,2},
{-1,-2},
{2,1},
{2,-1},
{-2,1},
{-2,-1}
};
void bfs()
{
while(!qx.empty())
{ //一直循环到队列为空
dx=qx.front();
dy=qy.front();
qx.pop(); //出队
qy.pop(); //出队
for(k=0;k<8;k++)
{
i=dir[k][0];
j=dir[k][1];
if(i+dx>=1 && i+dx<=n && j+dy>=1 && j+dy<=m && !a[i+dx][j+dy])
{ //判断 是 否 越界 或 已经遍历过
qx.push(i+dx); //入队
qy.push(j+dy); //入队
a[i+dx][j+dy]=a[dx][dy]+1; //步数 为 上一次 加1
}
} //这个for循环用来把马跳到没有遍历到的地方去
}
}
int main()
{
scanf("%d %d %d %d",&n,&m,&p,&q);
qx.push(p); //横坐标入队
qy.push(q); //纵坐标入队
a[p][q]=1; //步数从1开始,方便判断
bfs(); //广 搜
for(p=1;p<=n;p++)
{
for(q=1;q<=m;q++)
printf("%-5d",a[p][q]? a[p][q]-1:-1); /*输出 步数 时 要减1;*/
/* %-md: 输出格式为整形,长度为m(输出 最小 长度) ,
左 对 齐;可用m表示你的3,4,5,121;*/
cout<<endl;
}
return 0;
}
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
queue <int> qx; //定义横坐标队列
queue <int> qy; //定义纵坐标队列
int n,m,a[405][405]; //存放步数
int i,j,k,dx,dy,p,q;
const int dir[8][2]={ //状态转移数组==方向向量
{1,2},
{1,-2},
{-1,2},
{-1,-2},
{2,1},
{2,-1},
{-2,1},
{-2,-1}
};
void bfs()
{
while(!qx.empty())
{ //一直循环到队列为空
dx=qx.front();
dy=qy.front();
qx.pop(); //出队
qy.pop(); //出队
for(k=0;k<8;k++)
{
i=dir[k][0];
j=dir[k][1];
if(i+dx>=1 && i+dx<=n && j+dy>=1 && j+dy<=m && !a[i+dx][j+dy])
{ //判断 是 否 越界 或 已经遍历过
qx.push(i+dx); //入队
qy.push(j+dy); //入队
a[i+dx][j+dy]=a[dx][dy]+1; //步数 为 上一次 加1
}
} //这个for循环用来把马跳到没有遍历到的地方去
}
}
int main()
{
scanf("%d %d %d %d",&n,&m,&p,&q);
qx.push(p); //横坐标入队
qy.push(q); //纵坐标入队
a[p][q]=1; //步数从1开始,方便判断
bfs(); //广 搜
for(p=1;p<=n;p++)
{
for(q=1;q<=m;q++)
printf("%-5d",a[p][q]? a[p][q]-1:-1); /*输出 步数 时 要减1;*/
/* %-md: 输出格式为整形,长度为m(输出 最小 长度) ,
左 对 齐;可用m表示你的3,4,5,121;*/
cout<<endl;
}
return 0;
}
相关文章推荐
- 图的遍历 洛谷p3916
- 洛谷Luogu-1443 马的遍历 (BFS) HQG_AC的博客
- 【搜索】洛谷 P1443 马的遍历
- 洛谷 P1443 马的遍历(bfs)
- 洛谷1443 马的遍历
- 洛谷 - P1443:马的遍历
- 洛谷 1443_马的遍历_bfs
- 洛谷 P1443 马的遍历
- 洛谷 18-03-14-P1443 马的遍历
- 洛谷P1443 马的遍历
- 洛谷P3916 图的遍历_graph
- 洛谷 P1443 马的遍历
- 洛谷 P1443 马的遍历
- 洛谷 P1443 马的遍历
- 洛谷 - P1443马的遍历
- 洛谷p1443 马的遍历
- 洛谷——P1443 马的遍历
- 洛谷 P1443 马的遍历(BFS)
- 洛谷1443 马的遍历 解题报告
- 洛谷 P1443 马的遍历