UVA 493 Knight Moves Solution
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
typedef pair<int,int> pii;
typedef pair<pii,int> piii;
bool visit[8][8];
int m,n;
int dx[]={-2,-2,-1,-1,1,1,2,2,},dy[]={-1,1,-2,2,-2,2,-1,1};
int bfs(char *str1,char *str2)
{
queue<piii> q;
pii p1;
piii p2;
int x=str1[0]-97,y=str1[1]-49,xf=str2[0]-97,yf=str2[1]-49;
p1=pair<int,int>(x,y);
p2=pair<pii,int>(p1,0);
q.push(p2);
int i,xx,yy,zz;
while(!q.empty())
{
p2=q.front();
q.pop();
p1=p2.first;
zz=p2.second+1;
x=p1.first;
y=p1.second;
for(i=0;i<8;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if(xx>=0 && xx<8 && yy>=0 && yy<8)
{
if(xx==xf && yy==yf)
{
return zz;
}
if(!visit[xx][yy])
{
visit[xx][yy]=true;
p1=pair<int,int>(xx,yy);
p2=pair<pii,int>(p1,zz);
q.push(p2);
}
}
}
}
return 0;
}
int main()
{
int i,j,res,x1,y1,x2,y2;
char str1[2],str2[2];
while(cin>>str1>>str2)
{
memset(visit,false,sizeof(visit));
if(strcmp(str1,str2)==0)
res=0;
else
res=bfs(str1,str2);
cout<<"To get from "<<str1<<" to "<<str2<<" takes "<<res<<" knight moves."<<endl;
}
return 0;
}
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
typedef pair<int,int> pii;
typedef pair<pii,int> piii;
bool visit[8][8];
int m,n;
int dx[]={-2,-2,-1,-1,1,1,2,2,},dy[]={-1,1,-2,2,-2,2,-1,1};
int bfs(char *str1,char *str2)
{
queue<piii> q;
pii p1;
piii p2;
int x=str1[0]-97,y=str1[1]-49,xf=str2[0]-97,yf=str2[1]-49;
p1=pair<int,int>(x,y);
p2=pair<pii,int>(p1,0);
q.push(p2);
int i,xx,yy,zz;
while(!q.empty())
{
p2=q.front();
q.pop();
p1=p2.first;
zz=p2.second+1;
x=p1.first;
y=p1.second;
for(i=0;i<8;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if(xx>=0 && xx<8 && yy>=0 && yy<8)
{
if(xx==xf && yy==yf)
{
return zz;
}
if(!visit[xx][yy])
{
visit[xx][yy]=true;
p1=pair<int,int>(xx,yy);
p2=pair<pii,int>(p1,zz);
q.push(p2);
}
}
}
}
return 0;
}
int main()
{
int i,j,res,x1,y1,x2,y2;
char str1[2],str2[2];
while(cin>>str1>>str2)
{
memset(visit,false,sizeof(visit));
if(strcmp(str1,str2)==0)
res=0;
else
res=bfs(str1,str2);
cout<<"To get from "<<str1<<" to "<<str2<<" takes "<<res<<" knight moves."<<endl;
}
return 0;
}
Comments
Post a Comment