알고리즘/구현

[swea] 1954. 달팽이 숫자(Java 풀이)

파프리카. 2023. 8. 21. 00:00

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

import java.util.Scanner;

public class Solution {
	// 우 하 좌 상
	static int[] dx = {0,1,0,-1};
	static int[] dy = {1,0,-1,0};
 	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for(int tc = 1; tc<=T;tc++) {
			int N = sc.nextInt();
			int[][] ans = new int[N][N];
			int x = 0;
			int y = 0;
			int d = 0; // 방향
			int cnt = 1; 
			// 숫자를 하나씩 집어넣자
			while(cnt<=N*N) {
				ans[x][y] = cnt++;
				int nx = x + dx[d];
				int ny = y + dy[d];
				// 경계를 벗어나거나 숫자가 이미 존재하면
				if(nx<0 || nx >=N || ny <0 || ny>=N || ans[nx][ny] !=0) {
					// 방향을 바꾸자
					d = (d+1)%4;
					nx = x + dx[d];
					ny = y + dy[d];
				}
				x = nx;
				y = ny;
			}
			
			System.out.printf("#%d\n",tc);
			for(int[] arr:ans) {
				for(int i : arr) {
					System.out.printf("%d ",i);
				}
				System.out.println();
			}
		}
		
	}

}

처음에는 규칙을 찾아서 for문으로 풀려고 했는데 계속 이상하게 나와서 결국 다른 사람의 풀이를 참고했다. while문으로 숫자가 N*N이 될 때까지 반복하면서 인덱스가 경계선을 넘거나 이미 다른 수가 있는 경우에는 방향을 바꿔가면서 대입하는 방법이다. 굉장히 심플하고 이해하기 쉬운 코드다.