Skip to content

Commit 47c681e

Browse files
committed
spiral-matrix
1 parent 44f4a6b commit 47c681e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

spiral-matrix/se6816.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
}

0 commit comments

Comments
 (0)