PS/BOJ

백준 1952 달팽이2 / JAVA

얍연구소장 2023. 4. 9.

https://www.acmicpc.net/problem/1952

 

1952번: 달팽이2

M줄 N칸으로 되어 있는 표 위에, 달팽이 모양으로 선을 그리려고 한다. 위의 그림은 M=5, N=3의 예이다. 이제 표의 왼쪽 위 칸(ㅇ)에서 시작하여, 오른쪽으로 선을 그려 나간다. 표의 바깥 또는 이미

www.acmicpc.net

 

>풀이

 

package boj;

import java.util.Scanner;

/*
 * 백준 1952 달팽이2
 * #브론즈1
 */
public class boj_1952 {
	
	static int M, N;
	static boolean[][] map;
	static int[] dx = {0,1,0,-1}; // 우, 하, 좌, 상
	static int[] dy = {1,0,-1,0}; // 우, 하, 좌, 상
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		M = sc.nextInt();
		N = sc.nextInt();
		
		map = new boolean[M][N];
		solution(0,0);
	}

	public static void solution(int x, int y) {
		int sum = 1;
		int cnt = 0;
		int dir = 0;
		map[x][y] = true;
		while(dir < 4) {
			
			if(sum == N*M) {
				System.out.println(cnt);
				return;
			}
			
			int nx = x + dx[dir];
			int ny = y + dy[dir];
			if(nx >= 0 && nx < M && ny >= 0 && ny < N && !map[nx][ny]) {
				sum++; // 이동칸 수
				map[nx][ny] = true;
				x = nx;
				y = ny;
			} else { // 방향회전
				cnt++;
				dir++;
			}
			
			// 상 방향 까지 모두 이동했다면 다시 우 방향으로 가기 위함
			if(dir >= 4) {
				dir = 0;
			}
		}
	}
}

'PS > BOJ' 카테고리의 다른 글

백준 5341 Pyramids / JAVA  (1) 2023.04.12
백준 2037 문자메시지 / JAVA  (0) 2023.04.11
백준 1524 세준세비 / JAVA  (0) 2023.04.05
백준 2292 벌집 / JAVA  (0) 2023.03.26
백준 2145 숫자 놀이 / JAVA  (0) 2023.03.25

댓글