Skip to content

Commit

Permalink
feat: 삼각 달팽이
Browse files Browse the repository at this point in the history
  • Loading branch information
rldnrl committed Oct 6, 2023
1 parent 0d41941 commit ecc8964
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/programmers/lv2/TriangleSnail.java
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;
}
}

0 comments on commit ecc8964

Please sign in to comment.