본문 바로가기

숨막히는 알고말고/문제 풀이

[SWEA] 달팽이 숫자

👀 문제 설명

문제

로그인해야 문제를 볼 수 있다.

 

✍🏻풀이

달팽이는 오른쪽, 아래, 왼쪽, 위를 순서대로 이동하므로, 방향대로 움직이게 하는 dx, dy 배열을 선언한다.

while문은 count가 N * N보다 작거나 같을 동안 실행된다.

while문 안에서는 현재 위치인 curX, curY와 dx, dy를 사용해 다음 위치를 가져온다.

만약, 다음 위치가 범위를 벗어나거나, 해당 위치의 값이 0이 아니라면 (이미 방문한 곳이라는 의미) dir 값을 그 다음으로 바꾼다.

nextX, nextY가 제대로 된 값이라면 curX, curY 위치의 값을 현재 count로 바꾸고, count + 1을 한 후, curX에 nextX를, curY에 nextY를 대입하면 된다.

 

코드

package swea;

// 달팽이 숫자 (https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE&problemTitle=%EB%8B%AC%ED%8C%BD%EC%9D%B4&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1 )

import java.io.*;

public class SWEA_1954 {
	
	private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	private static int T;
	private static int N;
	private static int[][] board;
	private static int[] dx = { 0, 1, 0, -1 }; // 오른쪽, 아래, 왼쪽, 위
	private static int[] dy = { 1, 0, -1, 0 };
	
	public static void main(String[] args) throws Exception {
		T = Integer.parseInt(br.readLine());
		
		for (int test_case = 1; test_case <= T; test_case++) {
			N = Integer.parseInt(br.readLine());
			board = new int[N][N];
			
			int curX = 0;
			int curY = 0;
			int dir = 0;
			int count = 1;
			
			while (count <= N * N) {
				int nextX = curX + dx[dir];
				int nextY = curY + dy[dir];
				
				if (nextX < 0 || nextX >= N || nextY < 0 || nextY >= N || board[nextX][nextY] != 0) {
					dir = (dir + 1) % 4;
					nextX = curX + dx[dir];
					nextY = curY + dy[dir];
				}
				
				board[curX][curY] = count;
				count++;
				curX = nextX;
				curY = nextY;
			}
			
			System.out.println("#" + test_case);
			for (int i = 0; i < N; i++) {
				for (int j = 0; j < N; j++) {
					System.out.print(board[i][j] + " ");
				}
				System.out.println();
			}
		}
	}
	
}