Advertisement
shakhawatt

spoj knight moves

Nov 6th, 2021
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6. int x,y;
  7.  
  8. };
  9.  
  10. int row[] = { 2, 2, -2, -2, 1, 1, -1, -1 };
  11. int col[] = { -1, 1, 1, -1, 2, -2, 2, -2 };
  12.  
  13. bool vis[100][100];
  14. int dis[100][100]={0};
  15.  
  16.  
  17. bool isValid(int x, int y, int N) {
  18. return (x >= 0 && x < N) && (y >= 0 && y < N);
  19. }
  20.  
  21.  
  22.  
  23. int bfs(Node src, Node dest, int N)
  24. {
  25.  
  26.  
  27. queue<Node> q;
  28.  
  29. q.push(src);
  30. vis[src.x][src.y]=1;
  31. dis[src.x][src.y]=0;
  32.  
  33. while(!q.empty())
  34. {
  35. Node node = q.front();
  36. q.pop();
  37.  
  38. int x = node.x;
  39. int y = node.y;
  40.  
  41.  
  42. // if the destination is reached, return distance
  43. if (x == dest.x && y == dest.y) {
  44. return dis[x][y];
  45. }
  46.  
  47. for (int i = 0; i < 8; i++)
  48. {
  49.  
  50. int x1 = x + row[i];
  51. int y1 = y + col[i];
  52.  
  53. if (isValid(x1, y1, N) && !vis[x1][y1])
  54. {
  55. q.push({x1, y1});
  56. vis[x1][y1]=1;
  57. dis[x1][y1]= dis[node.x][node.y]+1;
  58. }
  59.  
  60. }
  61. }
  62. return 1;
  63.  
  64. }
  65.  
  66.  
  67.  
  68. int main(int argc, char** argv)
  69. {
  70.  
  71.  
  72. #ifndef ONLINE_JUDGE
  73. freopen("input.txt", "r", stdin);
  74. freopen("output.txt", "w", stdout);
  75. #endif
  76.  
  77.  
  78. // N x N matrix
  79. int N = 8;
  80. int p;
  81.  
  82. std::map<char, int> m;
  83.  
  84. for (struct { int a; char b; } s = { 0, 'a' } ; s.a < 8; ++s.a, s.b++)
  85. {
  86. m[s.b]=s.a;
  87.  
  88. }
  89.  
  90.  
  91. cin>>p;
  92.  
  93. for (int i = 0; i < p; ++i)
  94. {
  95. string s1,s2;
  96. cin>>s1>>s2;
  97.  
  98. int srcX = m[s1[0]];
  99. int srcY = (s1[1]-'0')-1;
  100.  
  101.  
  102. int desX = m[s2[0]];
  103. int desY = (s2[1]-'0')-1;
  104.  
  105. //cout<<srcX<<srcY<<" "<<desX<<desY<<endl;
  106.  
  107. Node src = {srcX, srcY};
  108.  
  109. // destination coordinates
  110. Node dest = {desX, desY};
  111.  
  112. cout <<bfs(src, dest, N)<<endl;
  113.  
  114. memset(dis, 0, sizeof(dis));
  115. memset(vis, 0, sizeof(vis));
  116.  
  117.  
  118.  
  119. }
  120.  
  121.  
  122.  
  123. }
  124.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement