뮁이의 개발새발

[JAVA] 백준 7576 토마토 (BFS) 본문

Algorithm

[JAVA] 백준 7576 토마토 (BFS)

뮁뮁이 2021. 9. 24. 10:50

BFS 연습하기 좋은 문제..

근데 갯수세는거에서 조금 당황탔다... ㅠ.ㅠ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class bj7576 {

	static class node {
		int x;
		int y;

		public node(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}
	}

	// 왼오앞뒤
	static int[] deltax = { -1, 1, 0, 0 };
	static int[] deltay = { 0, 0, -1, 1 };

	static int M, N, ans, one, zero;
	static int[][] map;
	static boolean[][] visit;
	static Queue<node> queue;

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(in.readLine());
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());

		map = new int[N][M];
		visit = new boolean[N][M];
		queue = new LinkedList<>();

		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(in.readLine());
			for (int j = 0; j < M; j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
				if (map[i][j] == 1) {
					queue.add(new node(j, i));
					one++;
				}
			}
		}

		if (one == M * N) {
			System.out.println(0);
			return;
		}

		BFS();

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if (map[i][j] == 0) {
					System.out.println(-1);
					return;
				}
			}
		}

		System.out.println(ans - 1);

	}

	private static void BFS() {
		while (!queue.isEmpty()) {
			int size = queue.size();
			for (int k = 0; k < size; k++) {
				node temp = queue.poll();
				for (int i = 0; i < 4; i++) {
					int nx = temp.x + deltax[i];
					int ny = temp.y + deltay[i];

					if (nx <= -1 || ny <= -1 || nx >= M || ny >= N) {
						continue;
					}

					if (map[ny][nx] == -1) {
						continue;
					}

					if (!visit[ny][nx]) {
						queue.add(new node(nx, ny));
						one++;
						visit[ny][nx] = true;
					}
				}
			}
			ans++;
		}
	}
}
Comments