Kaidul

439 Knight Moves

Jan 9th, 2014
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define Max 9
  6.  
  7. int cost[Max][Max];
  8. bool visited[Max][Max];
  9.  
  10. int dirX[]= {-2, -1, 1, 2, 2, 1, -1, -2};
  11. int dirY[]= {-1,-2, -2, -1, 1, 2, 2, 1};
  12.  
  13. string source, dest;
  14.  
  15. struct point {
  16.     int x, y;
  17.     point() {}
  18.     point(int _x, int _y) {
  19.         x = _x, y = _y;
  20.     }
  21.     bool operator == (const point& A) const {
  22.         return x == A.x and y == A.y;
  23.     }
  24. };
  25.  
  26. bool isValid(int x, int y) {
  27.     return x >= 1 and x <= 8 and y >= 1 and y <= 8;
  28. }
  29.  
  30. void bfs(point src, point des) {
  31.     queue <point> q;
  32.     q.push(src);
  33.     cost[src.x][src.y] = 0;
  34.     int posX, posY;
  35.     point pop;
  36.     memset(visited, false, sizeof visited);
  37.     while( !q.empty() ) {
  38.         pop = q.front();
  39.         q.pop();
  40.         if(pop == des) {
  41.             cout<<"To get from " << source
  42.                 << " to " << dest
  43.                 << " takes " << cost[pop.x][pop.y] << " knight moves.\n";
  44.             return;
  45.         }
  46.         for(int i = 0; i< 8; i++) {
  47.             posX = pop.x + dirX[i];
  48.             posY = pop.y + dirY[i];
  49.             if(isValid(posX, posY)  and !visited[posX][posY]) {
  50.                 visited[posX][posY] = true;
  51.                 cost[posX][posY] = cost[pop.x][pop.y] + 1;
  52.                 q.push( point(posX, posY) );
  53.             }
  54.         }
  55.     }
  56. }
  57.  
  58. int main() {
  59.     while(cin >> source >> dest) {
  60.         bfs( point(source[0] - 96, source[1] - '0'), point(dest[0] - 96, dest[1] - '0'));
  61.     }
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment