Source code for submission s978

knight.cpp

  1. #include <iostream>
  2. #include <string>
  3. #include <queue>
  4. //#include <tuple>
  5.  
  6. #define uint unsigned int
  7.  
  8. int dx[] = {-1,1,2,2,1,-1,-2,-2};
  9. int dy[] = {-2,-2,-1,1,2,2,1,-1};
  10.  
  11. using namespace std;
  12.  
  13. int main()
  14. {
  15. uint r,c,gr,gc,lr,lc;
  16.  
  17. while(cin >> r >> c >> gr >> gc >> lr >>lc)
  18. {
  19. gr--; gc--; lr--; lc--;
  20.  
  21. if(gr == lr && gc == lc)
  22. {
  23. cout << "0" << endl;
  24. continue;
  25. }
  26.  
  27. unsigned int field[r][c];
  28. for(uint i = 0; i < r; i++)
  29. for(uint j = 0; j < c; j++)
  30. {
  31. field[i][j] = 1000;
  32. }
  33.  
  34. field[gr][gc] = 0;
  35.  
  36. queue<pair<uint,uint> > fronta;
  37. fronta.push(pair<uint,uint>(gr,gc));
  38.  
  39. bool found = false;
  40.  
  41. while(!fronta.empty() && !found)
  42. {
  43. pair<uint,uint> p = fronta.front();
  44. fronta.pop();
  45.  
  46. for(int i = 0; i < 8; i++)
  47. {
  48. int row = p.first + dy[i];
  49. int col = p.second + dx[i];
  50. if(row < 0 || col < 0 || row >= r || col >= c) continue;
  51.  
  52. if(field[row][col] == 1000)
  53. {
  54. uint dist = field[p.first][p.second] + 1;
  55. field[row][col] = dist;
  56. if(row == lr && col == lc)
  57. {
  58. found = true;
  59. cout << dist;
  60. }
  61. fronta.push(pair<uint,uint>(row,col));
  62. }
  63. }
  64. }
  65.  
  66. if(!found)
  67. cout << "impossible";
  68. cout << endl;
  69. }
  70.  
  71. return 0;
  72.  
  73. }
  74.