bfs简单题----Knight Moves(hdu 1372)
2016-09-12 19:41
369 查看
题目大意:骑士移动,以象棋中的“马走日”移动的方式一样。给你一个方阵,以字母a~h代表列,以数字1~8代表行。
输入两个字符串,一个代表起点,一个代表终点,求在方阵范围里从起点到终点至少要走多少步。#include <iostream>
#include <string>
#include <queue>
using namespace std;
int s1,s2,e1,e2;
string a,b;
int mark[10][10];
int rule[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
int x,y,step;
};
int bfs()
{
queue<node> que;
node pre,next;
pre.x=s1;
pre.y=s2;
pre.step=0;
mark[pre.x][pre.y]=1;
que.push(pre);
while(!que.empty())
{
pre=que.front();
que.pop();
if(pre.x==e1&&pre.y==e2) {return pre.step; break;}
for(int i=0;i<8;i++)
{
next=pre;
if(next.x+rule[i][0]>0&&next.x+rule[i][0]<9
&&next.y+rule[i][1]>0&&next.y+rule[i][1]<9&&mark[next.x+rule[i][0]][next.y+rule[i][1]]==0 )
{
next.x+=rule[i][0];
next.y+=rule[i][1];
next.step++;
mark[next.x][next.y]=1;
que.push(next);
}
}
}
return 0;
}
int main()
{
while(cin>>a>>b)
{
s1=a[0]-'a'+1;
s2=a[1]-'0';
e1=b[0]-'a'+1;
e2=b[1]-'0';
memset(mark,0,sizeof(mark));
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
return 0;
}
输入两个字符串,一个代表起点,一个代表终点,求在方阵范围里从起点到终点至少要走多少步。#include <iostream>
#include <string>
#include <queue>
using namespace std;
int s1,s2,e1,e2;
string a,b;
int mark[10][10];
int rule[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
int x,y,step;
};
int bfs()
{
queue<node> que;
node pre,next;
pre.x=s1;
pre.y=s2;
pre.step=0;
mark[pre.x][pre.y]=1;
que.push(pre);
while(!que.empty())
{
pre=que.front();
que.pop();
if(pre.x==e1&&pre.y==e2) {return pre.step; break;}
for(int i=0;i<8;i++)
{
next=pre;
if(next.x+rule[i][0]>0&&next.x+rule[i][0]<9
&&next.y+rule[i][1]>0&&next.y+rule[i][1]<9&&mark[next.x+rule[i][0]][next.y+rule[i][1]]==0 )
{
next.x+=rule[i][0];
next.y+=rule[i][1];
next.step++;
mark[next.x][next.y]=1;
que.push(next);
}
}
}
return 0;
}
int main()
{
while(cin>>a>>b)
{
s1=a[0]-'a'+1;
s2=a[1]-'0';
e1=b[0]-'a'+1;
e2=b[1]-'0';
memset(mark,0,sizeof(mark));
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
return 0;
}
相关文章推荐
- HDU 1372Knight Moves(简单的BFS)
- hdu 1372 Knight Moves 简单bfs
- HDU - 1372 Knight Moves ( 简单BFS + floodfill )
- hdu 1372 Knight Moves (简单bfs,囧!)
- HDU-1372 Knight Moves (BFS)
- HDU1372 Knight Moves(BFS)
- HDU 1372 Knight Moves,bfs
- hdu1372 Knight Moves(BFS)
- HDU ACM 1372 Knight Moves (BFS)
- HDU 1372--Knight Moves【BFS】
- hdu 1372 Knight Moves(bfs)
- HDU 1372 Knight Moves (BFS)
- HDU 1372 Knight Moves(BFS)
- (step4.2.1) hdu 1372(Knight Moves——BFS)
- Knight Moves(HDU 1372)(BFS)
- hdu 1372 Knight Moves(BFS)
- hdu 1372 Knight Moves (BFS)
- HDU 1372 Knight Moves ( BFS & DBFS )
- 【HDU 1372 Knight Moves(BFS)】
- hdu 1372&&uva 439 KnightMoves(bfs)