Minimum Knight moves !!!
Given below code is for nakanj spoj or minimum knight moves spoj.
Question is same as costly chess(CCHESS) problem of spoj.
#include <bits/stdc++.h>
using namespace std;
#define MP make_pair
int dist[100][100];
map<int , pair<int , int > > mp;
map<pair<int , int > , int > m;
void fill_distance(int v){
int path[8][2];
int x = mp[v].first , y = mp[v].second;
path[0][0] = x+2 , path[0][1] = y+1;
path[1][0] = x+2 , path[1][1] = y-1;
path[2][0] = x-2 , path[2][1] = y+1;
path[3][0] = x-2 , path[3][1] = y-1;
path[4][0] = x+1 , path[4][1] = y+2;
path[5][0] = x+1 , path[5][1] = y-2;
path[6][0] = x-1 , path[6][1] = y+2;
path[7][0] = x-1 , path[7][1] = y-2;
for(int i = 0 ; i < 8 ; i ++)
{
if(path[i][0] >= 0 && path[i][0] < 8 && path[i][1] >= 0 && path[i][1] < 8){
dist[v][m[MP(path[i][0] , path[i][1])]] = 1;
}
}
}
void pre(){
int k = 0;
for(int i = 0 ; i < 64 ; i++)
for(int j = 0 ; j < 64 ; j++){
dist[i][j] = 9999999;
dist[j][j] = 0;
}
for(int i = 0 ; i<64 ; i++){
fill_distance( i);
}
for(int k = 0 ; k < 64 ; k++)
for(int i = 0 ; i < 64 ; i++)
for(int j = 0 ; j < 64 ; j++)
dist[i][j] = min(dist[i][j] , dist[i][k] + dist[k][j]);
}
int main()
{
int k = 0;
for(int i = 0 ; i < 8 ; i++)
for(int j = 0 ; j < 8 ; j++){
mp[k] = MP(i , j);
m[MP(i , j)] = k;
k++;
}
pre();
int t;
scanf("%d ",&t);
while(t--){
char inp[10];
gets(inp);
int x, y , u ,v;
x = inp[0] - 97;
y = inp[1] - 49;
u = inp[3] - 97;
v = inp[4] - 49;
int source = m[MP(x,y)], dest = m[MP(u,v)];
printf("%d\n",dist[source][dest]) ;
}
return 0;
}
No comments:
Post a Comment
Your comment is valuable to us