Advertisement
nikunjsoni

1810

May 1st, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. /**
  2.  * // This is the GridMaster's API interface.
  3.  * // You should not implement it, or speculate about its implementation
  4.  * class GridMaster {
  5.  *   public:
  6.  *     bool canMove(char direction);
  7.  *     int move(char direction);
  8.  *     boolean isTarget();
  9.  * };
  10.  */
  11.  
  12. class Solution
  13. {
  14.     public:
  15.     bool t[50001];
  16.     int grid[50001];
  17.     int dx[4] = {1,0,-1,0};
  18.     int dy[4] = {0,1,0,-1};
  19.     string d = "RDLU";
  20.     int tx, ty;
  21.    
  22.     void dfs(GridMaster &master,int x,int y){
  23.         if(master.isTarget()) tx=x,ty=y;
  24.        
  25.         t[x*201+y]=true;
  26.         for(int i=0; i<4; i++){
  27.             int cx = x+dx[i];
  28.             int cy = y+dy[i];
  29.             if(master.canMove(d[i]) && !t[cx*201+cy]){
  30.                 grid[cx*201+cy] = master.move(d[i]);
  31.                 dfs(master, cx, cy);
  32.                 grid[x*201+y] = master.move(d[(i+2)%4]);
  33.             }
  34.         }
  35.     }
  36.    
  37.     int findShortestPath(GridMaster &master){
  38.         memset(t, false, sizeof(t));
  39.         dfs(master, 100, 100);
  40.         bool v[50001];
  41.         memset(v, false, sizeof(v));
  42.        
  43.         priority_queue<pair<int,int>,  vector<pair<int,int>>, greater<pair<int,int>>> q;
  44.         q.push({0, 100*201+100});
  45.         v[100*201+100]=true;
  46.        
  47.         while(!q.empty()){
  48.             pair<int,int> p=q.top();
  49.             q.pop();
  50.             int cost = p.first;
  51.             int x = p.second/201;
  52.             int y = p.second%201;
  53.             if(x==tx && y==ty) return cost;
  54.            
  55.             for(int i=0;i<4;i++){
  56.                 int cx = x+dx[i];
  57.                 int cy = y+dy[i];
  58.                 if(!v[cx*201+cy] && t[cx*201+cy]){
  59.                     q.push({cost+grid[cx*201+cy], cx*201+cy});
  60.                     v[cx*201+cy]=true;
  61.                 }
  62.             }
  63.         }
  64.         return -1;
  65.     }
  66. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement