[SW Expert Academy, SWEA 1954] 달팽이 숫자 (java)
Problem Solving/SWEA

[SW Expert Academy, SWEA 1954] 달팽이 숫자 (java)

728x90

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE&problemTitle=1954&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1

 

SW Expert Academy

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

swexpertacademy.com


※ SW Expert 아카데미의 문제를 무단 복제하는 것을 금지합니다.

728x90

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Solution {
	
    static int[][] arr;
    static int N;
	
	private static void snail(int x, int y, int d, int count) {
		
        // 동, 남, 서, 북
		int[] dx = {0, 1, 0, -1};
		int[] dy = {1, 0, -1, 0};
		
		arr[x][y] = count;
		if(count == N * N) return;
		
		int nx = x + dx[d];
		int ny = y + dy[d];
		
		if(nx >= 0 && nx < N && ny >= 0 && ny < N && arr[nx][ny] == 0) {
			snail(nx, ny, d, count + 1);
		}
        // 인덱스를 벗어나거나, 이미 수가 저장되어 있다면 방향을 바꾼다.
		else {
			d++;
			if(d > 3) d %= 4;
			snail(x, y, d, count);
		}
	}

	public static void main(String[] args) throws Exception{

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		// 테스트 케이스 입력
		int T = Integer.parseInt(br.readLine());
		for (int test_case = 1; test_case < T + 1; test_case++) {
			sb.append("#" + test_case + "\n");
			// N 입력
			N = Integer.parseInt(br.readLine());
			// N * N 배열
			arr = new int[N][N];
			
			// 배열 채우기
			snail(0, 0, 0, 1);
			
			for (int i = 0; i < N; i++) {
				for (int j = 0; j < N; j++) {
					sb.append(arr[i][j]);
					if(j != N - 1) sb.append(" ");
					else sb.append("\n");
				}
			}
		}
		
		System.out.println(sb);
	}

}
728x90