728x90
2023.07.19 - [Coding Test/programmers] - 삼각 달팽이 (리스트 반시계 방향으로 채우기)
import java.util.*;
class Solution {
public int[] solution(int n) {
int[][] triangle = new int[n][n];
int v=1; // 현재수
int r=0;
int c=0;
for (int d=0; d<n; d++){
for (int x=0; x<n-d; x++){
switch((d+1)%3){
case 0: r--; c--;
break;
case 1: r++;
break;
case 2: c++;
break;
}
triangle[r-1][c]=v++;
}
}
int[] answer = new int[v-1];
int idx = 0;
for (int i=0; i<n; i++){
for (int j=0; j<=i; j++){
if(triangle[i][j]!=0){
answer[idx++]=triangle[i][j];
}
}
}
return answer;
}
}
import java.util.*;
class Solution {
public static final int[] dx = {0,1,-1};
public 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||nx==-1||ny==n||ny==-1||triangle[ny][nx]!=0) {
d=(d+1)%3;
nx = x+dx[d];
ny = y+dy[d];
if(nx==n||nx==-1||ny==n||ny==-1||triangle[ny][nx]!=0) break;
}
x = nx;
y = ny;
}
int[] answer = new int[v-1];
int idx = 0;
for (int i=0; i<n; i++){
for (int j=0; j<=i; j++){
if(triangle[i][j]!=0){
answer[idx++]=triangle[i][j];
}
}
}
return answer;
}
}
728x90