Skip to content

Commit a59d354

Browse files
committed
Spiral Matrix
1 parent daa753f commit a59d354

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Time Complexity: O(m * n)
3+
Space Complexity: O(1)
4+
5+
ํ˜„์žฌ ์œ„์น˜๋ฅผ r, c๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋‚˜ํƒ€๋‚ด๊ณ , ์ด r, c๋ฅผ ์ง์ ‘ ์ œ์–ดํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ–‰๋ ฌ์„ ์ˆœํšŒํ•œ๋‹ค.
6+
*/
7+
class Solution {
8+
public List<Integer> spiralOrder(int[][] matrix) {
9+
List<Integer> ans = new ArrayList<>();
10+
11+
int m = matrix.length, n = matrix[0].length;
12+
int r = 0, c = 0;
13+
int[] dr = {0, 1, 0, -1};
14+
int[] dc = {1, 0, -1, 0};
15+
int d = 0;
16+
final int VISITED = -999;
17+
18+
while (ans.size() < m * n) {
19+
ans.add(matrix[r][c]);
20+
matrix[r][c] = VISITED;
21+
22+
int nr = r + dr[d];
23+
int nc = c + dc[d];
24+
if (nr < 0 || nr >= m || nc < 0 || nc >= n || matrix[nr][nc] == VISITED) {
25+
d = (d + 1) % 4;
26+
nr = r + dr[d];
27+
nc = c + dc[d];
28+
}
29+
r = nr;
30+
c = nc;
31+
}
32+
33+
return ans;
34+
}
35+
}

0 commit comments

Comments
ย (0)