문제 : https://www.acmicpc.net/problem/7576


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		// 가로
		int m = scan.nextInt();
		// 세로
		int n = scan.nextInt();
		Node arr[][] = new Node[n][m];

		int maxDay = 0;

		// 큐선언
		Queue queue = new LinkedList();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int value = scan.nextInt();
				arr[i][j] = new Node(j, i, value);
				if (value == 1) {
					queue.offer(arr[i][j]);
				}
			}
		}
		// 입력부

		while (!queue.isEmpty()) {
			//
			Node polledNode = queue.poll();
			Node[] toOfferNode = check(polledNode, m, n, arr);
			
			for (int i = 0; i < 4; i++) {
				if (toOfferNode[i] != null) {
					toOfferNode[i].value = 1;
					if(maxDay < toOfferNode[i].day) {
						maxDay = toOfferNode[i].day;
					}
					queue.offer(toOfferNode[i]);
				}
			}
			
//			System.out.println(polledNode);
//			System.out.println(queue.isEmpty());
		}
//		for (int i = 0; i < n; i++) {
//			for (int j = 0; j < m; j++) {
//				System.out.print(arr[i][j].value+"");
//			}
//			System.out.println();
//		}
//		
//		
//		for (int i = 0; i < n; i++) {
//			for (int j = 0; j < m; j++) {
//				System.out.printf("%2d",arr[i][j].day);
//			}
//			System.out.println();
//		}
//		
		
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if(arr[i][j].value == 0) {
					maxDay = -1;
				}
			}
		}
		System.out.println(maxDay);
		scan.close();
	}

	static Node[] check(Node node, int m, int n, Node[][] arr) {

		Node[] result = new Node[4];
		int x[] = { 0, 0, -1, 1 };
		int y[] = { -1, 1, 0, 0 };

		for (int i = 0; i < 4; i++) {
			int chkX = node.x + x[i];
			int chkY = node.y + y[i];
			if (chkX < 0 || chkY < 0 || chkX >= m || chkY >= n) {
				result[i] = null;
			} else {
				if (arr[chkY][chkX].value == 0) {
					arr[chkY][chkX].day = node.day+1;
					result[i] = arr[chkY][chkX];
//					System.out.println("추가할 노드 : " + result[i]);
				}
			}
		}
		return result;
	}

	static class Node {
		int x;
		int y;
		int value;
		int day = 0;

		public Node(int x, int y, int value) {
			this.x = x;
			this.y = y;
			this.value = value;
			if(value == -1 ) {
				this.day = -1;
			}
		}

		@Override
		public String toString() {
			return "Node [x=" + x + ", y=" + y + ", value=" + value + ", day="+day+"]";
		}
	}
}

+ Recent posts

"여기"를 클릭하면 광고 제거.