곽로그

[SWEA 1954, Java] 달팽이 숫자 본문

알고리즘/SWEA

[SWEA 1954, Java] 달팽이 숫자

일도이동 2020. 12. 2. 14:56
반응형

문제

swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE

 

SW Expert Academy

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

swexpertacademy.com

 

풀이

이동방향은 → ↓ ← ↑ 순서로 바뀐다. 방향이 바뀔 때는 map 밖을 벗어났거나, 이미 숫자가 적힌 map을 만났을 때이다. 이를 map의 각 칸에 적히는 숫자 num이 N*N 이하인 경우 반복한다.

 

1. 현재칸에 num을 적는다 

2. num을 1증가시킨다

3. 다음 칸을 구한다

4. 다음 칸에 이미 숫자가 적혀있거나, map경계 밖인 경우 방향을 바꾼다

5. num이 N*N을 초과할 때까지 반복한다 

 

 

코드

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

class Solution
{
    public static BufferedReader br;
	public static BufferedWriter bw;
	public static int T;
	public static int N;
	public static int[][] map;
	public static boolean[][] visited;
	public static int[] dx = {0,1,0,-1};
	public static int[] dy = {1,0,-1,0};
	public static void main(String args[]) throws Exception{
    	br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		T = Integer.parseInt(br.readLine());
		for(int t = 1; t<=T; t++) {
			N = Integer.parseInt(br.readLine());
			map = new int[N][N];
			visited = new boolean[N][N];
			numberingMap();
			printMap(t);
			
		}
		
	}
	
	public static void numberingMap() {
		int direction = 0;
		int num = 1;
		int currentX = 0;
		int currentY = 0;
		int nextX = 0;
		int nextY = 0;
		while(num<=N*N) {
			map[currentX][currentY] = num++;
			visited[currentX][currentY]  = true;
			
			nextX = currentX + dx[direction];
			nextY = currentY + dy[direction];
			
			if(nextX<0 || nextX >=N || nextY<0 || nextY>=N || visited[nextX][nextY]) {
				direction = (direction+1)%4;
				nextX = currentX + dx[direction];
				nextY = currentY + dy[direction];
			}
			
			currentX = nextX;
			currentY = nextY;
		}
	}
	
	public static void printMap(int testCase) throws IOException {
		StringBuffer sb = new StringBuffer();
		sb.append("#"+testCase+"\n");
		for(int r= 0 ;r<N; r++) {
			for(int c=0 ; c<N; c++) {
				sb.append(map[r][c]+" ");
			}
			sb.append("\n");
		}
		bw.write(new String(sb));
		bw.flush();
	}
}
반응형
Comments