-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package programmers.lv2; | ||
|
||
public class TriangleSnail { | ||
public static int[] solution(int n) { | ||
int[][] triangle = new int[n][n]; | ||
int x = 0; | ||
int y = 0; | ||
int v = 1; | ||
|
||
while (true) { | ||
// 아래로 이동 | ||
while (true) { | ||
triangle[y][x] = v++; | ||
if (y + 1 == n || triangle[y + 1][x] != 0) break; | ||
y++; | ||
} | ||
|
||
if (x + 1 == n || triangle[y][x + 1] != 0) break; // 오른쪽으로 이동하지 못하는 경우 | ||
x++; | ||
|
||
// 오른쪽으로 이동 | ||
while (true) { | ||
triangle[y][x] = v++; | ||
if (x + 1 == n || triangle[y][x + 1] != 0) break; | ||
x++; | ||
} | ||
if (triangle[y - 1][x - 1] != 0) break; // 왼쪽으로 이동하지 못하는 경우 | ||
x--; | ||
y--; | ||
|
||
// 왼쪽으로 이동 | ||
while (true) { | ||
triangle[y][x] = v++; | ||
if (triangle[y - 1][x - 1] != 0) break; | ||
y--; | ||
x--; | ||
} | ||
|
||
if (y + 1 == n || triangle[y + 1][x] != 0) break; // 아래쪽으로 이동하지 못하는 경우 | ||
y++; | ||
} | ||
|
||
int[] answer = new int[v - 1]; | ||
int index = 0; | ||
for (int i = 0; i < n; i++) { | ||
for (int j = 0; j <= i; j++) { | ||
answer[index++] = triangle[i][j]; | ||
} | ||
} | ||
|
||
return answer; | ||
} | ||
} |