885 Spiral Matrix III #251
-
Topics: You start at the cell You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all Return an array of coordinates representing the positions of the grid in the order you visited them. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 885. Spiral Matrix III <?php
function spiralMatrixIII($rows, $cols, $rStart, $cStart) {
// Initialize directions: right, down, left, up
$directions = [[0,1], [1,0], [0,-1], [-1,0]];
$result = [];
// Initial position
$r = $rStart;
$c = $cStart;
// Initial steps for each direction
$stepCount = 1;
$totalSteps = 0;
// The number of positions to cover
$totalPositions = $rows * $cols;
// Add the starting position
$result[] = [$r, $c];
$totalSteps++;
while ($totalSteps < $totalPositions) {
for ($i = 0; $i < 4; $i++) {
// Moving direction: east -> south -> west -> north
for ($j = 0; $j < $stepCount; $j++) {
$r += $directions[$i][0];
$c += $directions[$i][1];
// Check if within the bounds of the grid
if ($r >= 0 && $r < $rows && $c >= 0 && $c < $cols) {
$result[] = [$r, $c];
$totalSteps++;
if ($totalSteps == $totalPositions) {
return $result;
}
}
}
// Increase steps after every two directions (right and down; left and up)
if ($i == 1 || $i == 3) {
$stepCount++;
}
}
}
return $result;
}
// Example Usage:
print_r(spiralMatrixIII(1, 4, 0, 0)); // [[0,0],[0,1],[0,2],[0,3]]
print_r(spiralMatrixIII(5, 6, 1, 4)); // [[1,4],[1,5],[2,5],[2,4], ...]
?> Explanation:
This approach ensures that we visit every cell in the grid in the required spiral order. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
rows * cols
positions.Let's implement this solution in PHP: 885. Spiral…