diff --git a/2577. Minimum Time to Visit a Cell In a Grid b/2577. Minimum Time to Visit a Cell In a Grid new file mode 100644 index 0000000..0f469d4 --- /dev/null +++ b/2577. Minimum Time to Visit a Cell In a Grid @@ -0,0 +1,60 @@ +class Solution { +public: + int minimumTime(vector>& grid) { + + int m = grid.size(); + int n = grid[0].size(); + + vector visited(m * n, -1); + + priority_queue, vector>, + greater>> + q; + + q.push({0, 0}); + visited[0] = 0; + vector dir = {0, -1, 0, 1, 0}; + + if (grid[1][0] > 1 && grid[0][1] > 1) + return -1; + + while (q.size() > 0) { + + auto node = q.top(); + q.pop(); + + int row = node.second / n; + int col = node.second % n; + + int val = node.second; + + int t = node.first; + + if (row == m - 1 && col == n - 1) { + return t; + } + for (int j = 0; j < 4; j++) { + + int new_row = row + dir[j]; + int new_col = col + dir[j + 1]; + + if (new_row < 0 || new_row >= m || new_col < 0 || new_col >= n) + continue; + + int val = new_row * n + new_col; + if (visited[val] != -1) + continue; + + if (grid[new_row][new_col] <= t + 1) + visited[val] = t + 1; + else if ((t + 1) % 2 != grid[new_row][new_col] % 2) + visited[val] = grid[new_row][new_col] + 1; + else + visited[val] = grid[new_row][new_col]; + q.push({visited[val], val}); + } + } + + return -1; + } +};