Skip to content

Commit 380b1ae

Browse files
committed
add solution of spiral-matrix
1 parent d8fac4b commit 380b1ae

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.*;
2+
class Solution {
3+
public List<Integer> spiralOrder(int[][] matrix) {
4+
5+
List<Integer> result = new ArrayList<>();
6+
7+
int left = 0;
8+
int right = matrix[0].length - 1;
9+
int top = 0;
10+
int bottom = matrix.length - 1;
11+
12+
while (left <= right && top <= bottom) {
13+
14+
// ์œ„์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ์ƒ๋‹จ ๊ฒฝ๊ณ„๋ฅผ 1 ์ฆ๊ฐ€
15+
for (int y = left; y <= right; y++) {
16+
result.add(matrix[top][y]);
17+
}
18+
top++;
19+
20+
// ์ƒ๋‹จ ์ธ๋ฑ์Šค๊ฐ€ ํ•˜๋‹จ ์ธ๋ฑ์Šค ๋ณด๋‹ค ์ปค์ง€๋ฉด ์ˆœํšŒ ์ค‘๋‹จ
21+
if (top > bottom) break;
22+
23+
// ์šฐ์ธก ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ์šฐ์ธก ๊ฒฝ๊ณ„๋ฅผ 1 ๊ฐ์†Œ
24+
for (int x = top; x <= bottom; x++) {
25+
result.add(matrix[x][right]);
26+
}
27+
right--;
28+
29+
// ์šฐ์ธก ์ธ๋ฑ์Šค๊ฐ€ ์ขŒ์ธก ์ธ๋ฑ์Šค๋ณด๋‹ค ์ž‘์•„์ง€๋ฉด ์ˆœํšŒ ์ค‘๋‹จ
30+
if (right < left) break;
31+
32+
// ์•„๋ž˜์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ํ•˜๋‹จ ๊ฒฝ๊ณ„๋ฅผ 1 ๊ฐ์†Œ
33+
for (int y = right; y >= left; y--) {
34+
result.add(matrix[bottom][y]);
35+
}
36+
bottom--;
37+
38+
// ์™ผ์ชฝ ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ์ขŒ์ธก ๊ฒฝ๊ณ„๋ฅผ 1 ์ฆ๊ฐ€
39+
for (int x = bottom; x >= top; x--) {
40+
result.add(matrix[x][left]);
41+
}
42+
left++;
43+
44+
}
45+
return result;
46+
47+
}
48+
49+
}

0 commit comments

Comments
ย (0)