Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- using pii = pair<int, int>;
- public:
- int minimumTime(vector<vector<int>>& g) {
- int m = g.size(), n = g[0].size();
- if (g[1][0] > 1 && g[0][1] > 1) return -1;
- using a3i = array<int, 3>;
- // queue<a3i> q;
- priority_queue <a3i, vector<a3i>, greater<a3i>> q;
- if (g[1][0] <= 1) q.push({1, 1, 0});
- if (g[0][1] <= 1) q.push({1, 0, 1});
- int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
- vector<vector<int>> dist(m, vector<int>(n, INT_MAX / 2));
- dist[0][0] = 0;
- set<pii> vis;
- int ans = INT_MAX;
- while(!q.empty()) {
- auto [ts, x, y] = q.top(); q.pop();
- if (x == m - 1 && y == n - 1) ans = min(ans, dist[x][y]);
- ts = dist[x][y];
- if (vis.count({x, y})) continue;
- vis.insert({x, y});
- for (int i = 0; i < 4; ++i) {
- int nx = x + dir[i][0], ny = y + dir[i][1];
- if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
- if (g[nx][ny] <= ts + 1) {
- dist[nx][ny] = min(dist[nx][ny], ts + 1);
- q.push({ts + 1, nx, ny});
- } else {
- int nts = (g[nx][ny] - ts - 1) / 2 * 2 + ts;
- q.push({nts + 1, nx, ny});
- dist[nx][ny] = min(dist[nx][ny], nts + 1);
- }
- }
- }
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement