본문 바로가기
알고리즘/정올

백준 2636 치즈 (자바)

by 김어찐 2021. 9. 15.
728x90
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class algo_2636_김어진 {
	static int[][] dMove = {{-1,0},{0,1},{1,0},{0,-1}};
	static int N;
	static int M;
	public static void main(String[] args) throws IOException {
		System.setIn(new FileInputStream("input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		int time=0;
		int last = 0;
		st = new StringTokenizer(br.readLine());
		N =Integer.parseInt(st.nextToken());
		M =Integer.parseInt(st.nextToken());
		int[][] board = new int[N][M];
		boolean[][] airCheck = new boolean[N][M];
		for (int i = 0; i < N; i++) {
			board[i] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
		}
		while(true) {
			int tmpLast = boardCheck(board);
			if(tmpLast==0) break;
			last=tmpLast;
			removeCheese(board);
			time++;
		}
		System.out.println(time);
		System.out.println(last);
	}
	
	private static void removeCheese(int[][] board) {
		ArrayList<Integer[]> al = new ArrayList<>();
		
		Queue<Integer[]> q = new LinkedList<Integer[]>();
		q.add(new Integer[] {0,0});
		boolean[][] boardCheck = new boolean[N][M];
		boardCheck[0][0]=true;
		while(!q.isEmpty()) {
			Integer[] pos = q.poll();
			int x= pos[0];
			int y = pos[1];
			for (int i = 0; i < 4; i++) {
				int nx = x+dMove[i][0];
				int ny = y + dMove[i][1];
				if(nx>=0 && nx<N && ny>=0 &&ny<M &&!boardCheck[nx][ny]) {
					if(board[nx][ny]==0) {
						q.add(new Integer[] {nx,ny});		
					}
					else {
						al.add(new Integer[] {nx,ny});
					}
					boardCheck[nx][ny]=true;
				}
			}
		}
		for (Integer[] pos : al) {
			board[pos[0]][pos[1]] = 0;
		}
	}

	private static int boardCheck(int[][] board) {
		
		int count = 0;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if(board[i][j]==1) count++;
			}
		}
		return count;
	}
}
728x90