lelouche29

Knight_game_Samsung

Sep 18th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class que{
  5.     int row[1000];
  6.     int col[1000];
  7.     int front,rear;
  8.     public:
  9.         que(){
  10.             front=rear=0;
  11.         }
  12.         void push(int x, int y){
  13.             row[rear]=x;
  14.             col[rear]=y;
  15.             rear++;
  16.         }
  17.         void top(int &x, int &y){
  18.             x=row[front];
  19.             y=col[front];
  20.         }
  21.         void pop(){
  22.             front++;
  23.         }
  24.         bool empty(){
  25.             return front==rear;
  26.         }
  27.         int size(){
  28.             return rear-front;
  29.         }
  30. };
  31.  
  32. int r,c;
  33. int s1,s2,d1,d2;
  34.  
  35. bool valid(int x, int y, bool visited[100][100]){
  36.     if(x>=0 && x<r && y>=0 && y<c && visited[x][y]==false)
  37.         return true;
  38.     return false;
  39. }
  40.  
  41. int bfs(int s1, int s2, int d1, int d2){
  42.     bool visited[100][100]={false};
  43.  
  44.     int distance[1000][1000];
  45.     for(int i=0; i<1000; i++)
  46.         for(int j=0; j<1000; j++)
  47.             distance[i][j]=-1;
  48.  
  49.     que q;
  50.     q.push(s1,s2);
  51.     visited[s1][s2]=true;
  52.     distance[s1][s2]=0;
  53.  
  54.     while(!q.empty()){
  55.         int x, y;
  56.         q.top(x,y);
  57.         q.pop();
  58.  
  59.         int dx[]={1,2,2,1,-1,-2,-2,-1};
  60.         int dy[]={2,1,-1,-2,-2,-1,1,2};
  61.        
  62.         for(int i=0; i<8; i++){
  63.             int m=x+dx[i];
  64.             int n=y+dy[i];
  65.  
  66.             if(valid(m,n,visited)){
  67.                 q.push(m,n);
  68.                 visited[m][n]=true;
  69.                 distance[m][n] = distance[x][y] + 1;
  70.             }
  71.         }
  72.     }
  73.     return distance[d1][d2];
  74. }
  75.  
  76. int main() {
  77.     int t;
  78.     cin>>t;
  79.     while(t--){
  80.         cin>>r>>c;
  81.  
  82.         cin>>s1>>s2>>d1>>d2;
  83.         cout<<bfs(s1-1,s2-1,d1-1,d2-1)<<endl;
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment