search
HomeBackend DevelopmentPHP TutorialMinimum Time to Visit a Cell In a Grid

2577. Minimum Time to Visit a Cell In a Grid

Difficulty: Hard

Topics: Array, Breadth-First Search, Graph, Heap (Priority Queue), Matrix, Shortest Path

You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].

You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.

Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.

Example 1:

Minimum Time to Visit a Cell In a Grid

  • Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]
  • Output: 7
  • Explanation: One of the paths that we can take is the following:
    • at t = 0, we are on the cell (0,0).
    • at t = 1, we move to the cell (0,1). It is possible because grid[0][1]
    • at t = 2, we move to the cell (1,1). It is possible because grid[1][1]
    • at t = 3, we move to the cell (1,2). It is possible because grid[1][2]
    • at t = 4, we move to the cell (1,1). It is possible because grid[1][1]
    • at t = 5, we move to the cell (1,2). It is possible because grid[1][2]
    • at t = 6, we move to the cell (1,3). It is possible because grid[1][3]
    • at t = 7, we move to the cell (2,3). It is possible because grid[2][3]
    • The final time is 7. It can be shown that it is the minimum time possible.

Example 2:

Minimum Time to Visit a Cell In a Grid

  • Input: grid = [[0,2,4],[3,2,1],[1,0,4]]
  • Output: -1
  • Explanation: There is no path from the top left to the bottom-right cell.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2
  • 4 sup>5
  • 0 sup>5
  • grid[0][0] == 0

Hint:

  1. Try using some algorithm that can find the shortest paths on a graph.
  2. Consider the case where you have to go back and forth between two cells of the matrix to unlock some other cells.

Solution:

We can apply a modified version of Dijkstra's algorithm using a priority queue. This problem essentially asks us to find the shortest time required to visit the bottom-right cell from the top-left cell, where each move has a time constraint based on the values in the grid.

Approach:

  1. Graph Representation: Treat each cell in the grid as a node. The edges are the adjacent cells (up, down, left, right) that you can move to.

  2. Priority Queue (Min-Heap): Use a priority queue to always explore the cell with the least time required. This ensures that we are processing the cells in order of the earliest time we can reach them.

  3. Modified BFS: For each cell, we will check if we can move to its neighboring cells and update the time at which we can visit them. If a cell is visited at a later time than the current, we add it back into the queue with the new time.

  4. Early Exit: Once we reach the bottom-right cell, we can return the time. If we exhaust the queue without reaching it, return -1.

Let's implement this solution in PHP: 2577. Minimum Time to Visit a Cell In a Grid

<?php /**
 * @param Integer[][] $grid
 * @return Integer
 */
function minimumTime($grid) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example 1
$grid1 = [
    [0, 1, 3, 2],
    [5, 1, 2, 5],
    [4, 3, 8, 6]
];
echo minimumTime($grid1) . PHP_EOL; // Output: 7

// Example 2
$grid2 = [
    [0, 2, 4],
    [3, 2, 1],
    [1, 0, 4]
];
echo minimumTime($grid2) . PHP_EOL; // Output: -1
?>

Explanation:

  1. Priority Queue:

    The SplPriorityQueue is used to ensure that the cells with the minimum time are processed first. The priority is stored as -time because PHP's SplPriorityQueue is a max-heap by default.

  2. Traversal:

    Starting from the top-left cell (0, 0), the algorithm processes all reachable cells, considering the earliest time each can be visited (max(0, grid[newRow][newCol] - (time 1))).

  3. Visited Cells:

    A visited array keeps track of cells that have already been processed to avoid redundant computations and infinite loops.

  4. Boundary and Validity Check:

    The algorithm ensures we stay within the bounds of the grid and processes only valid neighbors.

  5. Time Calculation:

    Each move takes one second, and if the cell requires waiting (i.e., grid[newRow][newCol] > time 1), the algorithm waits until the required time.

  6. Edge Case:

    If the queue is exhausted and the bottom-right cell is not reached, the function returns -1.


Complexity Analysis

  1. Time Complexity:

    • Each cell is added to the priority queue at most once: O(m x n x log(m x n)), where m and n are the grid dimensions.
  2. Space Complexity:

    • The space for the priority queue and the visited array is O(m x n).

Example Runs

Input:

<?php /**
 * @param Integer[][] $grid
 * @return Integer
 */
function minimumTime($grid) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example 1
$grid1 = [
    [0, 1, 3, 2],
    [5, 1, 2, 5],
    [4, 3, 8, 6]
];
echo minimumTime($grid1) . PHP_EOL; // Output: 7

// Example 2
$grid2 = [
    [0, 2, 4],
    [3, 2, 1],
    [1, 0, 4]
];
echo minimumTime($grid2) . PHP_EOL; // Output: -1
?>

Input:

$grid = [
    [0, 1, 3, 2],
    [5, 1, 2, 5],
    [4, 3, 8, 6]
];
echo minimumTime($grid); // Output: 7

This solution is efficient and works well within the constraints.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Minimum Time to Visit a Cell In a Grid. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)