Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0e5bd33

Browse files
authored
Create 54-Spiral-Matrix.js
1 parent b8d47c9 commit 0e5bd33

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

javascript/54-Spiral-Matrix.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[]}
4+
*/
5+
var spiralOrder = function(matrix) {
6+
const results = []
7+
let startRow = 0, startCol = 0, endRow = matrix.length-1, endCol = matrix[0].length-1;
8+
9+
while(results.length < matrix.length * matrix[0].length) {
10+
11+
for(let col = startCol; col <= endCol; col++ ) {
12+
results.push(matrix[startRow][col])
13+
}
14+
15+
for(let row = startRow + 1; row <= endRow; row++) {
16+
results.push(matrix[row][endCol])
17+
}
18+
19+
for(let col = endCol - 1; col >= startCol; col--) {
20+
if(startRow === endRow) break;
21+
results.push(matrix[endRow][col])
22+
}
23+
24+
for(let row = endRow - 1; row >= startRow + 1; row--) {
25+
if(endCol === startCol) break;
26+
results.push(matrix[row][startCol])
27+
}
28+
29+
startRow++
30+
startCol++
31+
endRow--
32+
endCol--
33+
}
34+
35+
return results
36+
};

0 commit comments

Comments
 (0)