-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
78 lines (72 loc) · 1.67 KB
/
index.php
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
<?php
class Solution {
/**
* @param Integer $n
* @return Integer[][]
*/
function generateMatrix($n) {
if ($n === 0) {
return [];
}
$length = $n * $n;
$result = [];
$walkMatrix = [];
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($j === 0) {
array_push($result, [0]);
array_push($walkMatrix, [true]);
} else {
array_push($result[$i], 0);
array_push($walkMatrix[$i], true);
}
}
}
$dir = 0;
$points = [0, 0];
$i = 1;
while ($i < $length + 1) {
$result[$points[0]][$points[1]] = $i;
$i++;
$walkMatrix[$points[0]][$points[1]] = false;
switch ($dir) {
case 0:
if ($points[1] === $n - 1 || !$walkMatrix[$points[0]][$points[1] + 1]) {
$dir++;
$points[0]++;
} else {
$points[1]++;
}
break;
case 1:
if ($points[0] === $n - 1 || !$walkMatrix[$points[0] + 1][$points[1]]) {
$dir++;
$points[1]--;
} else {
$points[0]++;
}
break;
case 2:
if ($points[1] === 0 || !$walkMatrix[$points[0]][$points[1] - 1]) {
$dir++;
$points[0]--;
} else {
$points[1]--;
}
break;
case 3:
if ($points[0] === 0 || !$walkMatrix[$points[0] - 1][$points[1]]) {
$dir = 0;
$points[1]++;
} else {
$points[0]--;
}
break;
}
}
return $result;
}
}
$s = new Solution();
$result = $s->generateMatrix(2);
var_dump($result);