542. 01 Matrix #1210
-
Topics: Given an The distance between two cells sharing a common edge is Example 1:
Example 2:
Constraints:
Note: This question is the same as 1765. Map of Highest Peak |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We will use multi-source Breadth-First Search (BFS), where all the 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++) {
for ($j = 0; $j < $cols; $j++) {
if ($mat[$i][$j] === 0) {
$distance[$i][$j] = 0;
$queue[] = [$i, $j];
}
}
}
// BFS from all '0' cells
while (!empty($queue)) {
list($currentRow, $currentCol) = array_shift($queue);
foreach ($directions as $direction) {
$newRow = $currentRow + $direction[0];
$newCol = $currentCol + $direction[1];
// Check if the new cell is within bounds
if ($newRow >= 0 && $newRow < $rows && $newCol >= 0 && $newCol < $cols) {
// If a shorter distance is found, update it and enqueue the cell
if ($distance[$newRow][$newCol] > $distance[$currentRow][$currentCol] + 1) {
$distance[$newRow][$newCol] = $distance[$currentRow][$currentCol] + 1;
$queue[] = [$newRow, $newCol];
}
}
}
}
return $distance;
}
// Example usage:
$mat1 = [[0,0,0],[0,1,0],[0,0,0]];
$mat2 = [[0,0,0],[0,1,0],[1,1,1]];
echo updateMatrix($mat1) . "\n"; // Output: [[0,0,0],[0,1,0],[0,0,0]]
echo updateMatrix($mat2) . "\n"; // Output: [[0,0,0],[0,1,0],[1,2,1]]
?> Explanation:
Input and Output:Input 1: $mat1 = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]; Output 1:
Input 2: $mat2 = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 1]
]; Output 2:
This solution is efficient with a time complexity of O(m × n), as each cell is processed once. The space complexity is also O(m × n) due to the |
Beta Was this translation helpful? Give feedback.
We will use multi-source Breadth-First Search (BFS), where all the
0
cells are treated as starting points (sources). For every1
cell, we calculate the minimum distance to the nearest0
.Let's implement this solution in PHP: 542. 01 Matrix