본문 바로가기

코딩테스트(백준)

[백준] 2638 : 치즈 -JAVA(자바) - 사좋배 공유

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

public class Main_치즈2 {

	static int arr[][];
	static int x;
	static int y;
	static int result;
	static int visit[][];
	static int dx[]= {-1,0,1,0};
	static int dy[] = {0,1,0,-1};
	static Queue q;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		x= sc.nextInt();
		y= sc.nextInt();
		sc.nextLine();
		arr= new int[x][y];
		visit= new int[x][y];
		q = new LinkedList();
		for(int i=0;i<x;i++) {
			for(int j=0;j<y;j++) {
				arr[i][j]=sc.nextInt();
			}
		}
		boolean ch =true;
		result=0;
		
		while(ch) {
			q.add(new pos(0,0));
			check_visit();
			BFS();
			result++;
			ch=false;
			loop:
			for(int i=0;i<x;i++) {
				for(int j=0;j<y;j++) {
					if(arr[i][j]!=0) {
						ch=true;
						break loop;
					}
				}
			}
		}
		System.out.println(result);
	}
	private static void check_visit() {
		for(int i=0;i<x;i++) {
			for(int j=0;j<y;j++) {
				visit[i][j]=0;
			}
		}
		
	}
	private static void BFS() {
		while(!q.isEmpty()) {
			pos temp = q.poll();
			for(int i=0;i<4;i++) {
				int rx = temp.x+dx[i];
				int ry = temp.y+dy[i];
				if(rx<0||ry<0||rx>=x||ry>=y) {
					continue;
				}
				if(arr[rx][ry]==0&&visit[rx][ry]==0) {
					visit[rx][ry]=1;
					q.add(new pos(rx,ry));
				}
				if(arr[rx][ry]==1) {
					visit[rx][ry]++;
					if(visit[rx][ry]>=2) {
						arr[rx][ry]=0;
					}
				}
			}
			
		}
	}
	private static class pos{
		int x;
		int y;
		pos(int x, int y){
			this.x=x;
			this.y=y;
		}
	}

}