hye-log

[SWEA]1954번 달팽이 숫자(JAVA) 본문

CodingTest/SWEA

[SWEA]1954번 달팽이 숫자(JAVA)

iihye_ 2023. 8. 6. 01:43

0. 문제 링크

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

 

SW Expert Academy

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

swexpertacademy.com

 

1. 문제 설명

1) N*N 크기에 오른쪽 -> 아래 -> 왼쪽 -> 위  순으로 숫자 출력하기

 

2. 입출력

// input
2 // 테스트 케이스의 개수
3
4

// output
#1
1 2 3
8 9 4
7 6 5
#2
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

 

3. 코드

import java.util.*;

public class swea1954 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		
		for(int t = 1; t <= T; t++) {
			int N = sc.nextInt();
			int[][] arr = new int[N][N];
			int k = N; 
			int r = 0; // 세로
			int c = -1; // 가로
			int num = 1; // 배열의 값
			
			while(k > 0) {
				for(int i = 0; i < k; i++) {
					arr[r][++c] = num++; // 가로 증가
				}
				k--; // 방향 바뀌면서 감소
				for(int i = 0; i < k; i++) {
					arr[++r][c] = num++; // 세로 증가
				}
				for(int i = 0; i < k; i++) {
					arr[r][--c] = num++; // 가로 감소
				}
				k--; // 방향 바뀌면서 감소
				for(int i = 0; i < k; i++) {
					arr[--r][c] = num++; // 세로 감소
				}
			}
			
			// 출력
			System.out.println("#"+t);
			for(int i = 0; i < N; i++) {
				for(int j = 0; j < N; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
		}
	}
}

 

실행 결과

 

4. 회고

1) 방향을 바꾸면서 작성하는 숫자의 개수가 달라짐을 이용하여 반복문으로 해결

 

5. Github

https://github.com/iihye/Algorithm/blob/main/SWEA/swea1954.java

728x90
Comments