
class Solution {
private static final int[] dx = {0, 1, -1};
private static final int[] dy = {1, 0, -1};
public int[] solution(int n) {
int[][] triangle = new int[n][n];
int v = 1;
int x = 0; int y = 0;
int d = 0;
while (true) {
triangle[y][x] = v++;
int nx = x + dx[d];
int ny = y + dy[d];
if (nx == n || ny == n || nx == -1 || ny == -1 || triangle[ny][nx] != 0) {
d = (d + 1) % 3;
nx = x + dx[d];
ny = y + dy[d];
if (nx == n || ny == n || nx == -1 || ny == -1 || triangle[ny][nx] != 0) break;
}
x = nx;
y = ny;
}
int[] result = new int[v - 1];
int idx = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
result[idx++] = triangle[i][j];
}
}
return result;
}
}
'Coding Test > 프로그래머스' 카테고리의 다른 글
[프로그래머스/자바] 시저 암호 (0) | 2023.11.23 |
---|---|
[프로그래머스/자바] 거리두기 확인하기 (0) | 2023.11.12 |
[프로그래머스/자바] 최대공약수와 최소공배수 (0) | 2023.11.07 |
[프로그래머스/MySQL] 자동차 대여 기록 별 대여 금액 구하기 (0) | 2023.10.07 |
[프로그래머스/자바] 영어 끝말잇기 (0) | 2023.10.07 |