티스토리 뷰

1954. 달팽이 숫자

swexpertacademy.com/main/solvingProblem/solvingProblem.do

 

SW Expert Academy

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

swexpertacademy.com

 

 

import java.util.Scanner;

public class SWEA1954 {
	// 210130
	// 1954. 달팽이 숫자

	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[][] arr = new int[N][N];

			int[] dx = { 1, 0, -1, 0 };
			int[] dy = { 0, 1, 0, -1 };

			arr[0][0] = 1;

			int num = 2;
			int i = 0;
			int j = 0;
			int d = 0;

			while (num <= N * N) {
				int ny = i + dy[d]; // 세로
				int nx = j + dx[d]; // 가로

				if (ny >= 0 && ny < N && nx >= 0 && nx < N && arr[ny][nx] == 0) {
					arr[ny][nx] = num++;
					i = ny;
					j = nx;
				} else {
					ny = i;
					nx = j;
					d = (d + 1) % 4;
				}
			}

			// 출력
			System.out.println("#" + tc);

			for (i = 0; i < N; i++) {
				for (j = 0; j < N; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}

		}

		sc.close();
	} // main
}

'코딩테스트 > SW Expert' 카테고리의 다른 글

[SWEA] 2001. 파리 퇴치  (0) 2021.01.30
[SWEA] 1284. 수도 요금 경쟁  (0) 2021.01.30
[SWEA] 2007. 패턴 마디의 길이  (0) 2021.01.29
[SWEA] 1926. 간단한 369게임  (0) 2021.01.29
[SWEA] 1859. 백만 장자 프로젝트  (0) 2021.01.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함