백준 1913

hong030·2023년 3월 8일
0
  • 실버 3단계 문제

풀이)

배열에서 1은 가운데 arr[N/2][N/2] 위치에 삽입된다.
1을 기준으로 북쪽 1칸, 동쪽 1칸, 남쪽 2칸, 서쪽 2칸, 북쪽 3칸, 동쪽 3칸, 남쪽 4칸, 서쪽 4칸... 이렇게 방향성을 가지고 숫자를 채워넣는다.

  1. int dir 을 만들어 0일 때는 북쪽, 1일 때는 동쪽, 2일 때는 남쪽, 3일 때는 서쪽을 의미하게 한다.
  2. int len을 만들어 1칸을 갈지 2칸을 갈지 의미하게 한다.
  3. 예를 들어 dir이 0, len이 3이면 북쪽으로 3칸 가야 한다는 뜻이다.

주의할 점)

배열 출력할 때 단순히 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);
	}
}

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글