풀이)
배열에서 1은 가운데 arr[N/2][N/2] 위치에 삽입된다.
1을 기준으로 북쪽 1칸, 동쪽 1칸, 남쪽 2칸, 서쪽 2칸, 북쪽 3칸, 동쪽 3칸, 남쪽 4칸, 서쪽 4칸... 이렇게 방향성을 가지고 숫자를 채워넣는다.
주의할 점)
배열 출력할 때 단순히 System.out.println(int)를 하면 메모리 초과가 뜬다.
StringBuilder을 통해 메모리를 최소한으로 줄여야 한다.
무언가를 출력할 때 Stringbuilder을 쓰는 습관을 들이자.
내 코드)
import java.io.*;
public class Backjoon1913 {
static int[][] makeSnail(int N){
int snail[][] = new int[N][N];
//북0 동1 남2 서3
int dir = 0;
int len = 1;
int i=1;
int row = N/2, col = N/2;
snail[row][col] = i;
while(true) {
if(dir==0) {
dir++;
for(int t=0;t<len;t++) {
row--; i++;
snail[row][col] = i;
if((row==0) &&(col==0))
return snail;
}
}else if (dir==1) {
dir++;
for(int t=0;t<len;t++) {
col++; i++;
snail[row][col] = i;
}
len++;
}
else if (dir==2) {
dir++;
for(int t=0;t<len;t++) {
row++; i++;
snail[row][col] = i;
}
}else {
dir = 0;
for(int t=0;t<len;t++) {
col--; i++;
snail[row][col] = i;
}
len++;
dir=0;
}
}
}
static void printArr(int [][]arr, int N, int T) {
StringBuilder str = new StringBuilder();
int row=0, col=0;
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
str.append(arr[i][j] + " ");
if (T == arr[i][j]) {
row = i+1; col=j+1;
}
}
str.append("\n");
}
str.append(row + " " + col);
System.out.println(str);
}
public static void main(String[]args) throws Exception{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
int T = Integer.parseInt(bf.readLine());
int[][]arr = makeSnail(N);
printArr(arr, N, T);
}
}