Advertisement
nikunjsoni

499

May 3rd, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
  4.         int m = maze.size(), n = maze[0].size();
  5.         vector<vector<int>> dis(m, vector<int>(n, INT_MAX));
  6.         vector<vector<string>> path(m, vector<string>(n));
  7.        
  8.         // distance of starting point is 0
  9.         dis[ball[0]][ball[1]] = 0;
  10.         queue<vector<int>> q;
  11.         q.push(ball);
  12.        
  13.        // the order of ball move direction is lexicographically smallest, i.e. dlru
  14.         vector<int> d1({1, 0, 0, -1}), d2({0, -1, 1, 0});
  15.         string dirs = "dlru";
  16.        
  17.         while(!q.empty()) {
  18.             int row = q.front()[0], col = q.front()[1];
  19.             q.pop();
  20.             for(int i = 0; i < 4; ++i) {
  21.                 int r = row+d1[i], c = col+d2[i], len = 0;
  22.                 while(r >= 0 && r < m && c >= 0 && c < n && maze[r][c] == 0) {
  23.                     r += d1[i];
  24.                     c += d2[i];
  25.                     len++;
  26.                 }
  27.                 r -= d1[i];
  28.                 c -= d2[i];
  29.                
  30.                 // if the current move goes across the hole
  31.                 if((hole[0]-row)*(hole[0]-r) <= 0 && (hole[1]-col)*(hole[1]-c) <= 0) {
  32.                     int k = abs(hole[0]-row)+abs(hole[1]-col);
  33.                     if(dis[hole[0]][hole[1]] > dis[row][col]+k || (dis[hole[0]][hole[1]] == dis[row][col]+k && path[hole[0]][hole[1]] > path[row][col]+dirs[i])) {
  34.                         dis[hole[0]][hole[1]] = dis[row][col]+k;
  35.                         path[hole[0]][hole[1]] = path[row][col]+dirs[i];
  36.                     }
  37.                     continue;
  38.                 }
  39.                
  40.                 // check whether the end point should be a new starting point
  41.                 if (dis[r][c] > dis[row][col]+len || (dis[r][c] == dis[row][col]+len && path[r][c] > path[row][col]+dirs[i])) {
  42.                     dis[r][c] = dis[row][col]+len;
  43.                     path[r][c] = path[row][col]+dirs[i];
  44.                     q.push({r, c});
  45.                 }
  46.             }
  47.         }
  48.         return path[hole[0]][hole[1]] == "" ? "impossible" : path[hole[0]][hole[1]];
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement