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+ import java .util .ArrayList ;
2+ import java .util .List ;
3+
4+ class Solution {
5+ public List <Integer > res = new ArrayList <>();
6+ public boolean [][] visit ;
7+
8+ public List <Integer > spiralOrder (int [][] m ) {
9+ int min = Math .min (m .length , m [0 ].length );
10+ int w = m .length ;
11+ int h = m [0 ].length ;
12+
13+ visit = new boolean [w ][h ];
14+
15+ for (int i = 0 ; i < (min / 2 ) + 1 ; i ++) {
16+ spiralDepth (i , m );
17+ }
18+
19+ return res ;
20+ }
21+
22+ public void spiralDepth (int d , int [][] m ) {
23+ int w = m [0 ].length ;
24+ int h = m .length ;
25+
26+ for (int i = d ; i < (w - d ); i ++) {
27+ visit (d , i , m );
28+ }
29+
30+ for (int i = d + 1 ; i < h - d ; i ++) {
31+ visit (i , w - d - 1 , m );
32+ }
33+
34+ // NOTE: 우측하단 에서 왼쪽으로 이동하거나, 좌하단에서 위로 이동할 때 가로(혹은 세로)가 1일때 방어하는 로직
35+ if ((h - d - 1 ) != d ) {
36+ // 우상단 에서 아래로 내려오면서 우 하단 구석 인덱스는 출력했기 때문에 - 2를 뺴주고, 왼쪽의 끝까지 출력해야하기 때문에 >= 연산을 사용해 for 반복횟수결정
37+ for (int i = w - d - 2 ; i >= d ; i --) {
38+ visit (h - d - 1 , i , m );
39+ }
40+ }
41+
42+ if ((w - d - 1 ) != d ) {
43+ for (int i = h - d - 2 ; i > d ; i --) {
44+ visit (i , d , m );
45+ }
46+ }
47+ }
48+
49+ public void visit (int x , int y , int [][] m ) {
50+ if (!visit [x ][y ]) {
51+ visit [x ][y ] = true ;
52+ res .add (m [x ][y ]);
53+ }
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments