File tree 2 files changed +71
-0
lines changed
2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @description Return spiral matrix.
3
+ * @param {Number } total number of row and column.
4
+ * @returns {Array [Number][] }
5
+ */
6
+ function spiralMatrix ( N ) {
7
+ const result = [ ]
8
+
9
+ for ( let i = 0 ; i < N ; i ++ ) {
10
+ result . push ( new Array ( N ) . fill ( null ) )
11
+ }
12
+
13
+ let top = 0 ,
14
+ level = 0
15
+ let count = 1
16
+
17
+ while ( true ) {
18
+ result [ level ] [ top ] = count
19
+
20
+ const upLevel = result [ level - 1 ] ,
21
+ bottomLevel = result [ level + 1 ] ,
22
+ leftLevel = result [ level ] ,
23
+ rightLevel = result [ level ]
24
+
25
+ const up = upLevel ? upLevel [ top ] : undefined
26
+ const bottom = bottomLevel ? bottomLevel [ top ] : undefined
27
+ const left = leftLevel ? leftLevel [ top - 1 ] : undefined
28
+ const right = rightLevel ? rightLevel [ top + 1 ] : undefined
29
+
30
+ if ( right === null && up !== null ) {
31
+ top ++
32
+ } else if ( right === null && up === null ) {
33
+ level --
34
+ } else if ( right !== null && bottom === null ) {
35
+ level ++
36
+ } else if ( right !== null && bottom !== null && left === null ) {
37
+ top --
38
+ } else if ( right !== null && bottom !== null && up === null ) {
39
+ level --
40
+ } else {
41
+ break
42
+ }
43
+
44
+ count ++
45
+ }
46
+
47
+ return result
48
+ }
49
+
50
+ module . exports = spiralMatrix ;
Original file line number Diff line number Diff line change
1
+ import { expect } from 'vitest'
2
+ import spiralMatrix from '../spiralMatrix'
3
+
4
+ describe ( 'spiralMatrix' , ( ) => {
5
+ test ( 'should return spiral matrix' , ( ) => {
6
+ const result = spiralMatrix ( 3 )
7
+ const expected = [
8
+ [ 1 , 2 , 3 ] ,
9
+ [ 8 , 9 , 4 ] ,
10
+ [ 7 , 6 , 5 ]
11
+ ]
12
+
13
+ expect ( result . length ) . toBe ( expected . length )
14
+
15
+ for ( let i = 0 ; i < expected . length ; i ++ ) {
16
+ for ( let j = 0 ; j < expected [ i ] . length ; j ++ ) {
17
+ expect ( result [ i ] [ j ] ) . toBe ( expected [ i ] [ j ] )
18
+ }
19
+ }
20
+ } )
21
+ } ) ;
You can’t perform that action at this time.
0 commit comments