-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrixSpiral.js
62 lines (54 loc) · 1.31 KB
/
matrixSpiral.js
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
(function(){
function spiral(number){
const result = [];
let startCol = 0;
let endCol = number - 1;
let startRow = 0;
let endRow = number - 1;
let value = 1;
for(let i = 0; i < number; i++){
result.push([]);
}
while(startCol <= endCol && startRow <= endRow){
for(let i = startCol; i <= endCol; i++){
result[startRow][i] = value;
value++;
}
startRow++;
for(let i = startRow; i <= endRow; i++){
result[i][endCol] = value;
value++;
}
endCol--;
for(let i = endCol; i >= startCol; i--){
result[endRow][i] = value;
value++;
}
endRow--;
for(let i = endRow; i >= startRow; i--){
result[i][startCol] = value;
value++;
}
startCol++;
}
return result;
}
console.log(spiral(3));
/*
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]
*/
console.log(spiral(5));
/*
[
[ 1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]
]
*/
})();