카테고리 없음

[SWEA] 1954. 달팽이 숫자 in Java

여니's 2022. 8. 2. 14:29

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

 

SW Expert Academy

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

swexpertacademy.com


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

public class Solution {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int T=Integer.parseInt(br.readLine());
		for(int t=1; t<=T; t++) {
			int n=Integer.parseInt(br.readLine());
			int[][] array=new int[n][n];
			int[] dxs= {0,1,0,-1}; // 우,하,좌,상
			int[] dys= {1,0,-1,0};
			int dir=0; // 우
			int x=0;
			int y=-1;
			
			for(int i=1; i<=n*n; i++) {
				x+=dxs[dir];
				y+=dys[dir];
				array[x][y]=i;
				int nx=x+dxs[dir];
				int ny=y+dys[dir];
				if (nx>=0 && nx<n && ny>=0 && ny<n && array[nx][ny]==0) {
					continue;
				}
				dir=(dir+1)%4;
				
			}
			
			System.out.println("#"+t);
			for(int i=0; i<n; i++) {
				for(int j=0; j<n; j++) {
					System.out.print(array[i][j]+" ");
				}
				System.out.println();
			}
		}
	}
}