mickypinata

IPST59: Min Turn Run

Jul 12th, 2021 (edited)
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef pair<int, int> pii;
  5. typedef tuple<int, int, int, int> tpp;
  6.  
  7. pii dir[3] = {pii(1, 0), pii(-1, 0), pii(0, 1)}; // UP DOWN RIGHT
  8. int row, col;
  9.  
  10. bool isInBoard(int r, int c){
  11.     return r >= 1 && r <= row && c >= 1 && c <= col;
  12. }
  13.  
  14. int main(){
  15.  
  16.     int st;
  17.     scanf("%d%d%d", &row, &col, &st);
  18.     char board[row + 1][col + 2];
  19.     int dist[row + 1][col + 1][3];
  20.     bool visited[row + 1][col + 1][3];
  21.  
  22.     for(int i = 1; i <= row; ++i){
  23.         for(int j = 1; j <= col; ++j){
  24.             scanf(" %c", &board[i][j]);
  25.         }
  26.     }
  27.     for(int i = 1; i <= row; ++i){
  28.         for(int j = 1; j <= col; ++j){
  29.             for(int d = 0; d < 3; ++d){
  30.                 dist[i][j][d] = 1e9;
  31.                 visited[i][j][d] = false;
  32.             }
  33.         }
  34.     }
  35.  
  36.     deque<tpp> dq;
  37.     dist[st][1][2] = 0;
  38.     dq.emplace_back(0, st, 1, 2);
  39.     while(!dq.empty()){
  40.         int ur = get<1>(dq.front());
  41.         int uc = get<2>(dq.front());
  42.         int us = get<3>(dq.front());
  43.         dq.pop_front();
  44.         if(uc == col){
  45.             cout << dist[ur][uc][us];
  46.             return 0;
  47.         }
  48.         if(visited[ur][uc][us]){
  49.             continue;
  50.         }
  51.         visited[ur][uc][us] = true;
  52.         for(int d = 0; d < 3; ++d){
  53.             int vr = ur + dir[d].first;
  54.             int vc = uc + dir[d].second;
  55.             int w = (us == d) ? 0 : 1;
  56.             if(isInBoard(vr, vc) && board[vr][vc] != '#' && !visited[vr][vc][d] && dist[ur][uc][us] + w < dist[vr][vc][d]){
  57.                 dist[vr][vc][d] = dist[ur][uc][us] + w;
  58.                 if(w == 0){
  59.                     dq.emplace_front(dist[vr][vc][d], vr, vc, d);
  60.                 } else {
  61.                     dq.emplace_back(dist[vr][vc][d], vr, vc, d);
  62.                 }
  63.             }
  64.         }
  65.     }
  66.     cout << "-1";
  67.  
  68.     return 0;
  69. }
  70.  
Add Comment
Please, Sign In to add comment