본문 바로가기

코딩테스트(백준)

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


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

public class Main {

	static int x;
	static int y;
	static int arr[][];
	static int visit[][];
	static Queueq;
	static int result;
	static int dx[]= {-1,0,1,0};
	static int dy[] = {0,1,0,-1};

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		x= sc.nextInt();
		y= sc.nextInt();
		arr= new int[x][y];
		visit = new int[x][y];
		result = 0;
		int count=0;
		q=new LinkedList();
		for(int i=0;i<x;i++) {
			for(int j=0;j<y;j++) {
				arr[i][j]=sc.nextInt();
				if(arr[i][j]==1) {
					count++;
				}
			}
		}
		
		boolean ch = true;
		int min=count;
		while(ch) {
			q.add(new pos(0,0));
			visit[0][0]=1;
			check();
			BFS();
		
			int cnt=0;
			ch= false;
			for(int i=0;i<x;i++) {
				for(int j=0;j<y;j++) {
					if(arr[i][j]==1) {
						cnt++;
					}
				}
			}
			if(cnt!=0) {
				min=cnt;
				ch=true;
			}
			if(cnt==0) {
				break;
			}
		}
		System.out.println(result);
		System.out.println(min);
	}

	private static void BFS() {
		result++;
		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]>=1) {
						arr[rx][ry]=0;	
					}
				}
			}
		}
	}
	private static void check() {
		for(int i=0;i<x;i++) {
			for(int j=0;j<y;j++) {
				visit[i][j]=0;
			}
		}
	}
	private static class pos{
		int x;
		int y;
		pos(int x, int y){
			this.x = x;
			this.y = y;
		}
	}
}