poj1915 简单bfs
来源:互联网 发布:linux程序设计第4版pdf 编辑:程序博客网 时间:2024/05/01 20:30
Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him canmove knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves neededfor a knight to reach one point from another, so that you have the chance to befaster than Somurolov.
For people not familiar with chess, the possible knight moves are shown inFigure 1.
Input
The input begins with the number n of scenarios on asingle line by itself.
Next follow n scenarios. Each scenario consists of three lines containinginteger numbers. The first line specifies the length l of a side of the chessboard (4 <= l <= 300). The entire board has size l * l. The second andthird line contain pair of integers {0, ..., l-1}*{0, ..., l-1} specifying thestarting and ending position of the knight on the board. The integers areseparated by a single blank. You can assume that the positions are validpositions on the chess board of that scenario.
Output
For each scenario of the input you have to calculate theminimal amount of knight moves which are necessary to move from the startingpoint to the ending point. If starting point and ending point areequal,distance is zero. The distance must be written on a single line.
Sample Input
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
Sample Output
5
28
0
题目分析:求象棋中,“马”从一个点跳到另一个点的最少步数。用bfs求最短路径。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
bool vis[310][310];//标记数组
int n;
intdx[]={-1,-2,-2,-1,1,2,2,1},dy[]={2,1,-1,-2,-2,-1,1,2};//方向数组
struct P{//点类
int x,y;
};
struct Node{//队元素
Px;
int step;
};
int bfs(P a,P b){
memset(vis,false,sizeof(vis));
vis[a.x][a.y]=true;
Node now,next;
now.x=a;now.step=0;
queue<Node> q;//用队列实现bfs
q.push(now);
while(!q.empty()){
now=q.front();q.pop();
if(now.x.x==b.x && now.x.y==b.y){
return now.step;
}
for(int i=0;i<8;++i){
int xx=next.x.x=now.x.x+dx[i],yy=next.x.y=now.x.y+dy[i];
next.step=now.step+1;
if(xx>=0 && xx<n && yy>=0 && yy<n&& !vis[xx][yy]){
vis[xx][yy]=true;
q.push(next);
}
}
}
return 0;
}
int main()
{
int t;scanf("%d",&t);
while(t--){
scanf("%d",&n);
P a,b;
scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y);
int ans=bfs(a,b);
printf("%d\n",ans);
}
return 0;
}
- poj1915 简单bfs
- poj1915 BFS
- poj1915 bfs
- POJ1915 BFS
- POJ1915 BFS&双向BFS
- POJ1915 经典bfs
- (未)poj1915(bfs)
- POJ1915:Knight Moves(BFS)
- POJ1915 (Knight Moves) BFS
- poj1915之BFS
- poj1915~双向bfs和bfs
- POJ1915 Knight Moves 经典BFS
- BFS广度优先搜索 poj1915
- poj1915 Knight Moves(bfs)
- poj1915 Knight Moves(bfs)
- poj1915--Knight Moves(初级BFS)
- POJ1915(Knight Moves,双向BFS)
- POJ1915
- 使用 Google V8 引擎开发可定制的应用程序
- WCF技术简单入门
- jsp,java项目邮箱注册发送邮件
- hadoop 处理日志
- 【第七章·查找技术】思维导图
- poj1915 简单bfs
- svn ubuntu
- Lombok(1.14.8)的简单示例
- easyui-accordion 设置默认选项卡
- ★★★同时支持iexplorer和firefox的javascript复制拷贝信息到剪贴板方法
- 虚拟机界面大小自适应设置
- 《数据结构》实验五 树和二叉树
- FRM-92101: Form 打不开报错
- x.509 PKCS12 PKCS7