LeetCode 2577: Minimum Time to Visit a Cell In a Grid Solution

Master LeetCode problem 2577 (Minimum Time to Visit a Cell In a Grid), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2577. Minimum Time to Visit a Cell In a Grid

Problem Explanation

Explanation:

To solve this problem, we can use Dijkstra's algorithm with a priority queue. We start from the top-left cell and iterate through all possible moves to find the minimum time required to reach the bottom-right cell. We maintain a priority queue to explore cells based on the minimum time taken to reach them. We update the time in each cell if it is less than the current time plus the time taken to move to that cell. :

Solution Code

import java.util.*;

class Solution {
    public int minTimeToVisitAllCells(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);
        pq.offer(new int[]{0, 0, 0});
        
        boolean[][] visited = new boolean[m][n];
        visited[0][0] = true;
        
        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int row = curr[0], col = curr[1], time = curr[2];
            
            if (row == m - 1 && col == n - 1) {
                return time;
            }
            
            for (int[] dir : directions) {
                int newRow = row + dir[0];
                int newCol = col + dir[1];
                
                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && !visited[newRow][newCol]) {
                    visited[newRow][newCol] = true;
                    int newTime = Math.max(time, grid[newRow][newCol]);
                    pq.offer(new int[]{newRow, newCol, newTime});
                }
            }
        }
        
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2577 (Minimum Time to Visit a Cell In a Grid)?

This page provides optimized solutions for LeetCode problem 2577 (Minimum Time to Visit a Cell In a Grid) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2577 (Minimum Time to Visit a Cell In a Grid)?

The time complexity for LeetCode 2577 (Minimum Time to Visit a Cell In a Grid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2577 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2577 in Java, C++, or Python.

Back to LeetCode Solutions