哈理工OJ 1367 King【基础入门BFS】
2016-02-15 18:26
489 查看
King | ||||||
| ||||||
Description | ||||||
The king in the chessboard wonders the least number of moves to go to square t from squares. The king can move one square at a time in any direction (8 directions). Help him to solve this problem! | ||||||
Input | ||||||
There are multiple test cases. The first line of input is an integer T indicating the number of test cases. Then T test cases follow. For each test case: Line 1. This line contains the chessboard coordinates of position s indicating the square the king is currently in. Line 2. This line contains the chessboard coordinates of position t indicating the square the king wants to go to. The coordinate consists of a lowercase letter from a to h and a digit from 1 to 8. | ||||||
Output | ||||||
For each test case: Line 1. Output the least number of moves. | ||||||
Sample Input | ||||||
1 a1 h8 | ||||||
Sample Output | ||||||
7 | ||||||
Source | ||||||
哈理工2012春季校赛 - 网络预选赛 |
另外注意处理输入的部分,把a变成1,把h变成8那样修改输入就行了、
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct zuobiao
{
int x,y;
}now,nex;
int ex,ey;
int sx,sy;
int vis[9][9];
int output[9][9];
int fx[8]={-1,-1,0,1,1,1,0,-1};
int fy[8]={0,1,1,1,0,-1,-1,-1};
void bfs(int x,int y)
{
queue<zuobiao >s;
memset(output,0,sizeof(output));
memset(vis,0,sizeof(vis));
vis[x][y]=1;
now.x=x;
now.y=y;
s.push(now);
while(!s.empty())
{
now=s.front();
if(now.x==ex&&now.y==ey)
{
printf("%d\n",output[now.x][now.y]);
return ;
}
s.pop();
for(int i=0;i<8;i++)
{
nex.x=now.x+fx[i];
nex.y=now.y+fy[i];
if(nex.x>=1&&nex.x<=8&&nex.y>=1&&nex.y<=8&&vis[nex.x][nex.y]==0)
{
vis[nex.x][nex.y]=1;
output[nex.x][nex.y]=output[now.x][now.y]+1;
s.push(nex);
}
}
}
return ;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[3],b[3];
scanf("%s%s",a,b);
sx=(a[0]-'a')+1;
sy=a[1]-'0';
ex=b[0]-'a'+1;
ey=b[1]-'0';
bfs(sx,sy);
}
}
相关文章推荐
- 在 Tomcat 中使用 JSTL
- LeetCode 217. Contains Duplicate 哈希
- iOS事件分发机制(一) hit-Testing
- JDK的快速排序算法实现DualPivotQuicksort
- 深入理解jQuery插件开发
- awk
- C++学习之primer
- 事务补偿机制
- vagrant学习笔记 - 基本命令的使用
- UIActivityIndicatorView 的使用
- 第3章 python实战例子 第一节
- 匿名内部类 类名规则 定位$1
- ':app:transformClassesWithDexForDebug'. > com.android.build.transform.api.TransformException: when i
- JSP 中的 Error Page
- BeanShell Assertion in Jmeter
- 跟我一起学JQuery插件开发教程
- 第一篇
- cache 和 buffer 有什么不同
- poj2184 Cow Exhibition(01背包+变化)
- Linux安装JDK和配置环境变量