Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 675ad78

Browse files
Create Spiral-matrix.js (ignacio-chiazzo#18)
1 parent 3a19885 commit 675ad78

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

LeetcodeProblems/Spiral-matrix.js

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
https://leetcode.com/problems/spiral-matrix/description/
3+
4+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
5+
6+
Example 1:
7+
8+
Input:
9+
[
10+
[ 1, 2, 3 ],
11+
[ 4, 5, 6 ],
12+
[ 7, 8, 9 ]
13+
]
14+
Output: [1,2,3,6,9,8,7,4,5]
15+
Example 2:
16+
17+
Input:
18+
[
19+
[1, 2, 3, 4],
20+
[5, 6, 7, 8],
21+
[9,10,11,12]
22+
]
23+
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
24+
*/
25+
26+
/**
27+
* @param {number[][]} matrix
28+
* @return {number[]}
29+
*/
30+
31+
var spiralOrder = function(matrix) {
32+
if(matrix.length === 0)
33+
return [];
34+
var retArray = [];
35+
const rowLength = matrix.length;
36+
const colLength = matrix[0].length;
37+
const countRectangles = Math.ceil(Math.min(colLength, rowLength)/2)
38+
for(var i = 0; i < countRectangles; i++) {
39+
printRect(matrix, i, rowLength, colLength, retArray);
40+
}
41+
return retArray;
42+
};
43+
44+
var printRect = function(matrix, i, rowLength, colLength, retArray) {
45+
const firstRow = i;
46+
const firstCol = i;
47+
const lastRow = rowLength - i - 1;
48+
const lastCol = colLength - i - 1;
49+
50+
for(var col = firstCol; col <= lastCol; col++) {
51+
retArray.push(matrix[firstRow][col]);
52+
}
53+
for(var row = firstRow + 1; row <= lastRow; row++) {
54+
retArray.push(matrix[row][lastCol]);
55+
}
56+
if(firstRow === lastRow || firstCol === lastCol) {
57+
return;
58+
}
59+
for(var col = lastCol - 1; col >= firstCol; col--) {
60+
retArray.push(matrix[lastRow][col]);
61+
}
62+
for(var row = lastRow - 1; row > firstRow; row--) {
63+
retArray.push(matrix[row][firstCol]);
64+
}
65+
}
66+
67+
var main = function() {
68+
const matrix = [
69+
[ 1, 2, 3 ],
70+
[ 4, 5, 6 ],
71+
[ 7, 8, 9 ]
72+
]
73+
74+
console.log(spiralOrder(matrix));
75+
}
76+
77+
main();
78+
module.exports.main = main;

0 commit comments

Comments
 (0)