Tuesday, February 07, 2012

FloodFill With BFS using Knight moves

/***
    Knight moves Made by
    Author : Md.Saiful Islam
***/


#include<stdio.h>


int boa[10][10],que[65][2],flg,cost[65];
int x[]={-2,-2,-1,1,2,2,1,-1};
int y[]={-1,1,-2,-2,1,-1,2,2};


int Bfs(int c1,int r1,int c2,int r2)
{
if(c1==c2&&r1==r2)
return 0;
int h,t,i,c,r,tr,tc;
h=t=0;
que[h][0]=r1,que[h][1]=c1;
boa[r1][c1]=flg;
cost[h]=0;
h++;
while(t!=h)
{
r=que[t][0],c=que[t][1];
for(i=0;i<8;i++)
{
tr=r+x[i],tc=c+y[i];
if(tr>0&&tr<=8&&tc>0&&tc<=8&&boa[tr][tc]!=flg)
{
boa[tr][tc]=flg;
cost[h]=cost[t]+1;
if(tr==r2&&tc==c2)
return cost[h];
que[h][0]=tr,que[h][1]=tc;
h++;
}
}
t++;
}
return 0;
}


int main()
{
int r1,r2,n;
char c1,c2;
while(scanf("%c%d %c%d ",&c1,&r1,&c2,&r2) == 4)
{
flg++;
n=Bfs(c1-'a'+1,r1,c2-'a'+1,r2);
printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,r1,c2,r2,n);
}
return 0;
}
/*
Input:
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Output:
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
*/

No comments:

Post a Comment