Skip to content

Commit fbdd668

Browse files
committed
solution for spiral matrix III with php
1 parent 1bcf705 commit fbdd668

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Intuition
2+
<!-- Describe your first thoughts on how to solve this problem. -->
3+
- To traverse all the cells in a grid of size `rows * cols` starting from a specific position (`rStart`, `cStart`) in a spiral order, we can use an array of directions and a variable to keep track of the number of steps needed in each direction.
4+
- We will move in sequential directions: **right, down, left, and up**, increasing the number of steps after every two directions (one complete cycle).
5+
6+
# Approach
7+
8+
<!-- Describe your approach to solving the problem. -->
9+
- Initialize necessary variables such as the direction array, total number of cells, starting position, initial step count, and direction index.
10+
- Use a while loop to continue until we have added all the cells to the result array.
11+
- Inside the while loop, use a nested for loop. The outer loop runs twice for each direction (to ensure we change direction after every two edges), and the inner loop moves the required number of steps in the current direction.
12+
- Check if the new position is within the grid bounds, and if so, add that position to the result array.
13+
- After every two directions, increment the number of steps required.
14+
15+
# Complexity
16+
- Time complexity: **O(n×m)**
17+
18+
We will traverse all cells in the grid once, so the time complexity is linear with respect to the number of cells in the grid, or `O(n×m)`, where `n` is the number of rows and `m` is the number of columns.
19+
20+
- Space complexity: **O(n×m)**
21+
22+
The result array `ans` will contain all positions of the grid, so the space complexity is also linear with respect to the number of cells in the grid, or `O(n×m)`.
23+
24+
# Code
25+
```php
26+
class Solution
27+
{
28+
/**
29+
* @param Integer $rows
30+
* @param Integer $cols
31+
* @param Integer $rStart
32+
* @param Integer $cStart
33+
* @return Integer[][]
34+
*/
35+
public static function spiralMatrixIII($rows, $cols, $rStart, $cStart) {
36+
$directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
37+
$totalCells = $rows * $cols;
38+
$r = $rStart;
39+
$c = $cStart;
40+
$steps = 1;
41+
$directionIndex = 0;
42+
$ans = [[$r, $c]];
43+
44+
while (count($ans) < $totalCells) {
45+
for ($i = 0; $i < 2; $i++) {
46+
for ($j = 0; $j < $steps; $j++) {
47+
$r += $directions[$directionIndex][0];
48+
$c += $directions[$directionIndex][1];
49+
if ($r >= 0 && $r < $rows && $c >= 0 && $c < $cols) {
50+
$ans[] = [$r, $c];
51+
}
52+
}
53+
$directionIndex = ($directionIndex + 1) % 4;
54+
}
55+
$steps++;
56+
}
57+
return $ans;
58+
}
59+
}
60+
61+
```

0 commit comments

Comments
 (0)