File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ 구현을 통해 배열을 읽어들이는 방식
3+ 시간 복잡도 : O(N*M)
4+ 공간 복잡도 : O(N*M)
5+ */
6+ class Solution {
7+ int [] moveY = {1 , 0 , -1 , 0 };
8+ int [] moveX = {0 , -1 , 0 , 1 };
9+ int N ;
10+ int M ;
11+ public List <Integer > spiralOrder (int [][] matrix ) {
12+ N = matrix .length ;
13+ M = matrix [0 ].length ;
14+ boolean [][] visited = new boolean [N ][M ];
15+ List <Integer > result = new ArrayList <>();
16+ int curX = 0 ;
17+ int curY = 0 ;
18+ int direction = 0 ;
19+ int count = 0 ;
20+ visited [curX ][curY ] = true ;
21+ result .add (matrix [curX ][curY ]);
22+
23+ while (true ) {
24+ if (count == 4 ) {
25+ break ;
26+ }
27+ int tempX = curX + moveX [direction ];
28+ int tempY = curY + moveY [direction ];
29+ if (outOfIndex (tempX , tempY )) {
30+ direction = (direction + 1 ) % 4 ;
31+ count ++;
32+ continue ;
33+ }
34+
35+ if (visited [tempX ][tempY ]) {
36+ direction = (direction + 1 ) % 4 ;
37+ count ++;
38+ continue ;
39+ }
40+
41+ curX = tempX ;
42+ curY = tempY ;
43+ result .add (matrix [curX ][curY ]);
44+ visited [curX ][curY ] = true ;
45+
46+ count = 0 ;
47+ }
48+
49+ return result ;
50+ }
51+
52+ public boolean outOfIndex (int x , int y ) {
53+ return x < 0 || x >= N || y < 0 || y >= M ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments