Advertisement
shamiul93

UVa 439 - Knight Move

Feb 10th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include<iostream>
  2. #include<algorithm>
  3. #include<queue>
  4. #include<map>
  5. #include<vector>
  6. #include<cstdio>
  7. #include<cstdlib>
  8. #include<cstring>
  9.  
  10. using namespace std;
  11.  
  12. #define ll long long
  13.  
  14. #define PII pair<int,int>
  15.  
  16. int dx[] = { -2, -1, -2, -1, 1, 2, 2, 1 };
  17. int dy[] = { -1, -2, 1, 2, 2, 1, -1, -2 };
  18.  
  19. ll level[8][8] = {};
  20.  
  21. ll BFS(PII src, PII dst)
  22. {
  23.     queue< PII > q ;
  24.     q.push(src) ;
  25.     level[src.first][src.second] = 1 ;
  26.  
  27.     while(!q.empty())
  28.     {
  29.         PII now ;
  30.         now = q.front();
  31.         q.pop();
  32.  
  33.         for(ll i = 0 ; i< 8 ; i++)
  34.         {
  35.             ll tx, ty ;
  36.             tx = now.first + dx[i] ;
  37.             ty = now.second + dy[i] ;
  38.  
  39.             if(tx >= 0 && tx< 8 && ty >=0 && ty< 8 )
  40.             {
  41.                 if(level[tx][ty]==0)
  42.                 {
  43.                     level[tx][ty] = level[now.first][now.second] + 1 ;
  44.                     q.push(make_pair(tx, ty)) ;
  45.                 }
  46.                 else
  47.                 {
  48.                     if(level[tx][ty] > level[now.first][now.second] + 1)
  49.                     {
  50.                         level[tx][ty] = level[now.first][now.second] + 1 ;
  51.                     }
  52.                 }
  53.             }
  54.         }
  55.     }
  56.  
  57.     return level[dst.first][dst.second] ;
  58.  
  59. }
  60.  
  61. int main()
  62. {
  63. //    freopen("in.txt","r",stdin);
  64.     char s1[5], s2[5] ;
  65.     ll ans;
  66.     while(scanf(" %s %s", s1, s2)!= EOF)
  67.     {
  68.         ll r1, r2, c1, c2 ;
  69.         r1 = s1[1] - '0' - 1 ;
  70.         r2 = s2[1] - '0' -1 ;
  71.         c1 = s1[0] - 'a'  ;
  72.         c2 = s2[0] - 'a'  ;
  73.  
  74.         PII src, dst ;
  75.         src = make_pair(r1, c1) ;
  76.         dst = make_pair(r2, c2) ;
  77.  
  78.         ans = BFS(src,dst) - 1;
  79.  
  80.         printf("To get from %s to %s takes %lld knight moves.\n", s1, s2, ans ) ;
  81.  
  82.         memset(level, 0, sizeof(level));
  83.     }
  84.  
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement