-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSpiralMatrix.php
More file actions
90 lines (81 loc) · 2.61 KB
/
SpiralMatrix.php
File metadata and controls
90 lines (81 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
namespace leetcode;
class SpiralMatrix
{
public static function spiralOrder(array $matrix): array
{
if (empty($matrix) || empty($matrix[0])) {
return $matrix;
}
$ans = [];
[$rowi, $rown] = [0, count($matrix) - 1];
[$coli, $coln] = [0, count($matrix[0]) - 1];
while ($rowi <= $rown && $coli <= $coln) {
// col: i -> n -> [rowi][j]
for ($j = $coli; $j <= $coln; $j++) {
array_push($ans, $matrix[$rowi][$j]);
}
$rowi++;
// row: i -> n -> [j][coln]
for ($j = $rowi; $j <= $rown; $j++) {
array_push($ans, $matrix[$j][$coln]);
}
$coln--;
if ($rowi <= $rown) {
// col: n -> i -> [rown][j]
for ($j = $coln; $j >= $coli; $j--) {
array_push($ans, $matrix[$rown][$j]);
}
}
$rown--;
if ($coli <= $coln) {
// row: n -> i -> [j][coln]
for ($j = $rown; $j >= $rowi; $j--) {
array_push($ans, $matrix[$j][$coli]);
}
}
$coli++;
}
return $ans;
}
public static function spiralOrder2(array $matrix): array
{
if (empty($matrix) || empty($matrix[0])) {
return $matrix;
}
[$ans, $dir] = [[], 0];
[$rowi, $rown] = [0, count($matrix) - 1];
[$coli, $coln] = [0, count($matrix[0]) - 1];
while ($rowi <= $rown && $coli <= $coln) {
switch ($dir) {
case 0:
for ($col = $coli; $col <= $coln; $col++) {
array_push($ans, $matrix[$rowi][$col]);
}
$rowi++;
break;
case 1:
for ($row = $rowi; $row <= $rown; $row++) {
array_push($ans, $matrix[$row][$coln]);
}
$coln--;
break;
case 2:
for ($col = $coln; $col >= $coli; $col--) {
array_push($ans, $matrix[$rown][$col]);
}
$rown--;
break;
case 3:
for ($row = $rown; $row >= $rowi; $row--) {
array_push($ans, $matrix[$row][$coli]);
}
$coli++;
break;
}
$dir = ($dir + 1) % 4;
}
return $ans;
}
}