BJ2636 치즈

·2022년 4월 17일
0

백준 알고리즘

목록 보기
21/34

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

토마토 문제와 거의 유사하다.
BFS를 이용해서 구현하면 된다.

package day0330;

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

public class Cheese {

	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	static StringTokenizer st;
	static int[][] arr;
	static boolean[][] visited;
	static int X, Y, land;
	static int[] dir_x = { 0, 1, 0, -1 };
	static int[] dir_y = { -1, 0, 1, 0 };

	static class Point {
		int x;
		int y;

		Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}

	private static int count() {
		int sum = 0;
		for (int i = 0; i < X; i++) {
			for (int j = 0; j < Y; j++) {
				if (arr[i][j] == 1) {
					sum++;
				}
			}
		}
		return sum;
	}

	private static boolean isEmpty() {
		for (int i = 0; i < X; i++) {
			for (int j = 0; j < Y; j++) {
				if (arr[i][j] == 1) {
					return false;
				}
			}
		}
		return true;
	}

	private static void BFS(int x, int y) {
		Queue<Point> queue = new LinkedList<>();
		queue.add(new Point(x, y));
		visited[y][x] = true;

		while (!queue.isEmpty()) {
			int queueSize = queue.size();
			for (int i = 0; i < queueSize; i++) {
				Point p = queue.poll();
				for (int dic = 0; dic < 4; dic++) {
					int nx = p.x + dir_x[dic];
					int ny = p.y + dir_y[dic];

					if (nx < 0 || ny < 0 || nx >= Y || ny >= X) {
						continue;
					}

					if (arr[ny][nx] < 0) {
						continue;
					}

					if (!visited[ny][nx]) {
						if (arr[ny][nx] == 1) {
							arr[ny][nx] -= 10;
							continue;
						}
						visited[ny][nx] = true;
						queue.add(new Point(nx, ny));
					}
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		st= new StringTokenizer(br.readLine(), " ");
		X = Integer.parseInt(st.nextToken());
		Y = Integer.parseInt(st.nextToken());
		arr = new int[X][Y];
		for (int i = 0; i < X; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			for (int j = 0; j < Y; j++) {
				arr[i][j] = Integer.parseInt(st.nextToken());
			}
		}
		int time = 0, last = 0;
		while (!isEmpty()) {
			visited = new boolean[X][Y];
			last = count();
			BFS(0, 0);
			change();
			time++;
		}
		System.out.println(time);
		System.out.println(last);
	}

	private static void change() {
		for (int i = 0; i < X; i++) {
			for (int j = 0; j < Y; j++) {
				if (arr[i][j] < 0) {
					arr[i][j] = 0;
				}
			}
		}
	}

}
profile
SSAFY 7기

0개의 댓글