Skip to content

542. 01 Matrix #1210

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jan 22, 2025 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We will use multi-source Breadth-First Search (BFS), where all the 0 cells are treated as starting points (sources). For every 1 cell, we calculate the minimum distance to the nearest 0.

Let's implement this solution in PHP: 542. 01 Matrix

<?php
/**
 * @param Integer[][] $mat
 * @return Integer[][]
 */
function updateMatrix($mat) {
    $rows = count($mat);
    $cols = count($mat[0]);
    $directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];

    // Initialize distances with a large number for '1' cells
    $distance = array_fill(0, $rows, array_fill(0, $cols, PHP_INT_MAX));
    $queue = [];

    // Add all '0' cells to the queue and set their distance to 0
    for ($i = 0; $i < $rows; $i++) {…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 22, 2025
Maintainer Author

Answer selected by basharul-siddike
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 medium Difficulty
2 participants