Skip to content

1368. Minimum Cost to Make at Least One Valid Path in a Grid #1173

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use the 0-1 BFS approach. The idea is to traverse the grid using a deque (double-ended queue) where the cost of modifying the direction determines whether a cell is added to the front or back of the deque. The grid is treated as a graph where each cell has weighted edges based on whether its current direction matches the movement to its neighbors.

Let's implement this solution in PHP: 1368. Minimum Cost to Make at Least One Valid Path in a Grid

<?php
/**
 * @param Integer[][] $grid
 * @return Integer
 */
function minCost($grid) {
    $m = count($grid);
    $n = count($grid[0]);

    // Direction vectors for the signs (right, left, down, up)
    $directions = [
        [0, 1],  // 1…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@topugit
Comment options

topugit Jan 18, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Jan 18, 2025
Maintainer Author

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants