코딩테스트 문제

[SWEA] D2 | 달팽이문제 (JAVA)

아설아 2024. 5. 19. 02:25

.... 전 코딩에 소질 없는 것 같아요..

 

문제

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

 

SW Expert Academy

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

swexpertacademy.com

 

풀이

달팽이 문제. 뭐 풀긴 오래걸리긴했지만 제가 푼 거 보니 그러게 복잡한 알고리즘을 요하는 문제는 아닌 듯하다. 

방향벡터? 델타? 그것만 알고 있으면 된다. 배열로 만들어 놓고 풀기

 

코드

import java.util.Scanner;

class Solution {
	static int[] di = { 0, 1, 0, -1 };
	static int[] dj = { 1, 0, -1, 0 };

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

		Scanner sc = new Scanner(System.in);
		int T;
		T = sc.nextInt();

		for (int test_case = 1; test_case <= T; test_case++) {
			int N = sc.nextInt();
			int arr[][] = new int[N][N];
			int dr = 0;
			int i = 0, j = 0;
			int ni=0, nj=0;
			for(int n = 1; n<=N*N; n++) {
				arr[i][j] = n;
				if(i + di[dr]<0 || i + di[dr]>=N || j + dj[dr]<0 || j + dj[dr]>=N || arr[i + di[dr]][j + dj[dr]]!=0) {
					dr = (dr+1) % 4;
				}
				i+=di[dr];
				j+=dj[dr];
			}

			System.out.println("#"+test_case);
			for(int i1=0; i1<N; i1++) {
				for(int j1=0; j1<N; j1++)
					System.out.print(arr[i1][j1]+" ");
				System.out.println();
			}
		}
	}
}