1015 Knight Moves
2016-04-23 22:44
197 查看
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;
}
题意:国际象棋棋盘,给定起始点和重点,求最少移动次数。
思路:在国际象棋棋盘上,共有八个方向的移动位置,对每个移动方向,将其保存到队列中,因为队列逐层搜索,所以必定可以找到最短的路径。
感想:输入有些困难,要将字符和数字分开,通过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;
}
相关文章推荐
- jQuery源码学习之对象创建与初始化
- Oracle数据库触发器如何调用Java程序实现Openfire消息推送
- Spring配置文件异常:White spaces are required between publicId and systemId
- import com.sun.image.codec.jpeg.JPEGCodec不通过 Eclipse找不到包
- tty/pts 相关指令
- mysql客户端工具使用
- ZOJ 3933(网络流)
- 优酷 Java笔试题(摘要)
- 排序常用算法总结
- 这是一份沉重回忆的开始
- 搭建简单Samba服务器
- Java通用集合工具总结
- view
- 第一章 JAVA入门(JAVA与C/C++那些事)
- 标准I/O
- 搬家
- Generating Artifacts问题解决汇总
- 作业八
- 无谓的许诺
- 微距摄影-昆虫篇