Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct Node
- {
- int x,y;
- };
- int row[] = { 2, 2, -2, -2, 1, 1, -1, -1 };
- int col[] = { -1, 1, 1, -1, 2, -2, 2, -2 };
- bool vis[100][100];
- int dis[100][100]={0};
- bool isValid(int x, int y, int N) {
- return (x >= 0 && x < N) && (y >= 0 && y < N);
- }
- int bfs(Node src, Node dest, int N)
- {
- queue<Node> q;
- q.push(src);
- vis[src.x][src.y]=1;
- dis[src.x][src.y]=0;
- while(!q.empty())
- {
- Node node = q.front();
- q.pop();
- int x = node.x;
- int y = node.y;
- // if the destination is reached, return distance
- if (x == dest.x && y == dest.y) {
- return dis[x][y];
- }
- for (int i = 0; i < 8; i++)
- {
- int x1 = x + row[i];
- int y1 = y + col[i];
- if (isValid(x1, y1, N) && !vis[x1][y1])
- {
- q.push({x1, y1});
- vis[x1][y1]=1;
- dis[x1][y1]= dis[node.x][node.y]+1;
- }
- }
- }
- return 1;
- }
- int main(int argc, char** argv)
- {
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- // N x N matrix
- int N = 8;
- int p;
- std::map<char, int> m;
- for (struct { int a; char b; } s = { 0, 'a' } ; s.a < 8; ++s.a, s.b++)
- {
- m[s.b]=s.a;
- }
- cin>>p;
- for (int i = 0; i < p; ++i)
- {
- string s1,s2;
- cin>>s1>>s2;
- int srcX = m[s1[0]];
- int srcY = (s1[1]-'0')-1;
- int desX = m[s2[0]];
- int desY = (s2[1]-'0')-1;
- //cout<<srcX<<srcY<<" "<<desX<<desY<<endl;
- Node src = {srcX, srcY};
- // destination coordinates
- Node dest = {desX, desY};
- cout <<bfs(src, dest, N)<<endl;
- memset(dis, 0, sizeof(dis));
- memset(vis, 0, sizeof(vis));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement