File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the matrix,
2
+ // because every element is processed once.
3
+
4
+ // Space Complexity: O(m * n), where m is the number of rows and n is the number of columns in the matrix,
5
+ // because we store all matrix elements in the result array.
6
+
7
+ /**
8
+ * @param {number[][] } matrix
9
+ * @return {number[] }
10
+ */
11
+ var spiralOrder = function ( matrix ) {
12
+
13
+ let topRow = 0 ;
14
+ let bottomRow = matrix . length - 1 ;
15
+ let leftCol = 0 ;
16
+ let rightCol = matrix [ 0 ] . length - 1 ;
17
+ let result = [ ] ;
18
+
19
+ while ( topRow <= bottomRow && leftCol <= rightCol ) {
20
+ // move to the right
21
+ for ( let col = leftCol ; col <= rightCol ; col ++ ) {
22
+ result . push ( matrix [ topRow ] [ col ] ) ;
23
+ }
24
+
25
+ topRow += 1 ;
26
+
27
+ if ( topRow > bottomRow ) {
28
+ break ;
29
+ }
30
+
31
+ // move down
32
+ for ( let row = topRow ; row <= bottomRow ; row ++ ) {
33
+ result . push ( matrix [ row ] [ rightCol ] ) ;
34
+ }
35
+
36
+ rightCol -= 1 ;
37
+
38
+ if ( leftCol > rightCol ) {
39
+ break ;
40
+ }
41
+
42
+ // move to the left
43
+ for ( let col = rightCol ; col >= leftCol ; col -- ) {
44
+ result . push ( matrix [ bottomRow ] [ col ] ) ;
45
+ }
46
+
47
+ bottomRow -= 1 ;
48
+ if ( topRow > bottomRow ) {
49
+ break ;
50
+ }
51
+
52
+ // move up
53
+ for ( let row = bottomRow ; row >= topRow ; row -- ) {
54
+ result . push ( matrix [ row ] [ leftCol ] ) ;
55
+ }
56
+
57
+ leftCol += 1 ;
58
+
59
+ if ( leftCol > rightCol ) {
60
+ break ;
61
+ }
62
+ }
63
+
64
+ return result ;
65
+ } ;
66
+
You can’t perform that action at this time.
0 commit comments