[백준] 1013번 달팽이 (구현, java)

728x90
반응형

www.acmicpc.net/problem/1913

 

1913번: 달팽이

N개의 줄에 걸쳐 표를 출력한다. 각 줄에 N개의 자연수를 한 칸씩 띄어서 출력하면 되며, 자릿수를 맞출 필요가 없다. N+1번째 줄에는 입력받은 자연수의 좌표를 나타내는 두 정수를 한 칸 띄어서

www.acmicpc.net

밖이 아니라 안에서부터 빙글빙글 돌아나가는 문제이다. 

하반기 삼성 오후 2번째에서 이거 활용해서 나오는 문제가 나왔었는데

지금은 금방 풀었는데 시험장에서는 긴장해서 좀 버벅거렸다. ㅠㅠ

 

import java.util.Scanner;

public class B_1913_달팽이_Main {
	static int n,m;
	static int[][] map;
	static int[] ypos= {-1,0,1,0};
	static int[] xpos= {0,1,0,-1};
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
		map=new int[n][n];
		int ay=0,ax=0;
		int y=n/2;
		int x=n/2;
		int len=1;
		int num=1;
		int cnt=0;
		int dir=0;
		int total=0;
		while(true) {
			if(num==m) {
				ay=y;
				ax=x;
			}
			map[y][x]=num++;
			if(y==0 && x==0)break;
			cnt+=1;
			total+=1;
			y=y+ypos[dir];
			x=x+xpos[dir];
			if(cnt==len) {
				dir=(dir+1)%4;
				cnt=0;
			}
			if(total==2*len) {
				len+=1;
				total=0;
			}
		}
		
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(map[i][j]+" ");
			}
			System.out.println();
		}
		
		System.out.println((ay+1)+" "+(ax+1));
	}
}
728x90
반응형
TAGS.

Comments