1015 Knight Moves
来源:互联网 发布:iphone怎么授权软件 编辑:程序博客网 时间:2024/05/16 07:39
1015 Knight Moves
题意:国际象棋棋盘,给定起始点和重点,求最少移动次数。
思路:在国际象棋棋盘上,共有八个方向的移动位置,对每个移动方向,将其保存到队列中,因为队列逐层搜索,所以必定可以找到最短的路径。
感想:输入有些困难,要将字符和数字分开,通过getchar()读取字符这点比较重要。
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
struct node{
int x,y,cnt;
};
node s,e;
int a[9][9];
intdri[8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
int bfs(){
memset(a,0,sizeof(a));
node p,q;
s.cnt=0;
queue<node>b;
b.push(s);
a[s.x][s.y]=1;
while(!b.empty()){
p=b.front();
b.pop();
if(p.x==e.x&&p.y==e.y)
return p.cnt;
for(int i=0;i<8;i++){
q.x=p.x+dri[i][0];
q.y=p.y+dri[i][1];
if(q.x<1||q.x>8||q.y<1||q.y>8) continue;
if(a[q.x][q.y]==1) continue;
q.cnt=p.cnt+1;
a[q.x][q.y]=1;
b.push(q);
}
}
return -1;
}
int main(){
char row,w;
int col,l;
int min;
while(scanf("%c",&row)!=EOF){
scanf("%d",&col);
getchar();
scanf("%c%d",&w,&l);
getchar();
s.x=row-'a'+1;
s.y=col;
e.x=w-'a'+1;
e.y=l;
if(s.x==e.x&&s.y==e.y)
min=0;
else
min=bfs();
cout<<"To get from "<<row<<col<<"to "<<w<<l<<" takes "<<min<<"knight moves."<<endl;
}
return 0;
}
- 1015 Knight Moves
- 1015 Knight Moves
- 1015-Knight Moves
- acm 2 1015 Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- Knight Moves
- view
- Spring配置文件异常:White spaces are required between publicId and systemId
- 排序常用算法总结
- 深度优先搜索+解炸弹人游戏
- 优酷 Java笔试题(摘要)
- 1015 Knight Moves
- Oracle数据库触发器如何调用Java程序实现Openfire消息推送
- jQuery源码学习之对象创建与初始化
- 数值的整数次方
- Java语言的非对称加密的实现
- 文章标题
- C++静态多态性之函数重载
- 使用循环语句输出空心金字塔
- 关于编程语句i++与++i的区别用法