https://school.programmers.co.kr/learn/courses/30/lessons/68645
이차원 배열로 생각해보면
1 0 0 0
2 9 0 0
3 10 8 0
4 5 6 7
이렇게 생각할 수 있고
순서대로 ↓→↖ 으로 이동한다.
if(goX == n || goY == n || goX == -1 || goY == -1 || triangles[goX][goY] != 0){
d = (d + 1) % 3;
goX = x + moveX[d];
goY = y + moveY[d];
if(goX == n || goY == n || goX == -1 || goY == -1 || triangles[goX][goY] != 0){
break;
}
}
방향전환을 할때 d = (d + 1) % 3 으로 해결.
int[] moveX = {1, 0, -1}; int[] moveY = {0, 1, -1};
class Solution {
public int[] solution(int n) {
int[][] triangles = new int[n][n];
int[] moveX = {1, 0, -1};
int[] moveY = {0, 1, -1};
int x = 0;
int y = 0;
int d = 0;
int value = 1;
while(true){
triangles[x][y] = value++;
int goX = x + moveX[d];
int goY = y + moveY[d];
if(goX == n || goY == n || goX == -1 || goY == -1 || triangles[goX][goY] != 0){
d = (d + 1) % 3;
goX = x + moveX[d];
goY = y + moveY[d];
if(goX == n || goY == n || goX == -1 || goY == -1 || triangles[goX][goY] != 0){
break;
}
}
x = goX;
y = goY;
}
int[] answer = new int[value - 1];
int index = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
answer[index++] = triangles[i][j];
}
}
return answer;
}
}