forked from AllAlgorithms/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiralMatrix.js
More file actions
39 lines (34 loc) · 805 Bytes
/
spiralMatrix.js
File metadata and controls
39 lines (34 loc) · 805 Bytes
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
function getSpiralMatrix (n) {
const matrix = []
for (let i = 0; i < n; ++i) { matrix.push([]) }
let counter = 1
let startRow = 0
let endRow = n - 1
let startCol = 0
let endCol = n - 1
while (startCol <= endCol && startRow <= endRow) {
for (let i = startCol; i <= endCol; ++i) {
matrix[startRow][i] = counter
counter++
}
startRow++
for (let i = startRow; i <= endRow; ++i) {
matrix[i][endCol] = counter
counter++
}
endCol--
for (let i = endCol; i >= startCol; --i) {
matrix[endRow][i] = counter
counter++
}
endRow--
for (let i = endRow; i >= startRow; --i) {
matrix[i][startCol] = counter
counter++
}
startCol++
}
return matrix
}
const matrix = getSpiralMatrix(3)
console.log(matrix)