문법/알고리즘

bfs문제(토마토)

코딩 화이팅 2023. 4. 15. 23:11

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

package DFS_BFS;

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

public class bj_토마토_7576 {
	static int N,M,map[][],max;
	static boolean[][] visit;
	static int[] dy= {-1,1,0,0};
	static int[] dx= {0,0,-1,1};
	static Queue<int[]> q=new LinkedList<int[]>();
	
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		M=sc.nextInt();
		N=sc.nextInt();
		map=new int[N][M];
		visit=new boolean[N][M];
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				map[i][j]=sc.nextInt();				
			}
		}
		//입력 끝
		
		//바로 bfs함수를 시작하는 것이 아니라 
//		6 4
//		1 -1 0 0 0 0
//		0 -1 0 0 0 0
//		0 0 0 0 -1 0
//		0 0 0 0 -1 1
		//이런 입력이 있으므로 1인 값들을 일단 큐에 넣어준다.
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if (map[i][j]==1) {
					q.add(new int[] {i,j});
				}
			}
		}
		
		//bfs함수를 출력 안에 넣어 바로 출력할 수 있게 해준다.
		System.out.println(bfs());			
	}

	private static int bfs() {
		//원래는 여기에 큐를 선언하지만 지금 1인 값들은 이미 큐에 들어가 있는 상태
		
		//큐가 빌 때까지 반복 여기서부터는 원래대로
		//지금 위에 입력상태라면 0,0의 1과 마지막의 1이 하나씩 각각 아래로 위로 1로 채워지면서
		//하나씩 올라간다.
		while (!q.isEmpty()) {
			int[] now=q.poll();
			int nowy=now[0];
			int nowx=now[1];
			for (int i = 0; i < 4; i++) {
				int ny=nowy+dy[i];
				int nx=nowx+dx[i];
				if (ny>=0&&nx>=0&&ny<N&&nx<M) {
					if (!visit[ny][nx]&&map[ny][nx]==0) {						
						map[ny][nx]=map[nowy][nowx]+1;
						q.add(new int[] {ny,nx});
						visit[ny][nx]=true;
					}
				}
			}
		}
		
		//여기까지 while문이 마치면 이제 모든 값들은 1로 채워져있거나
		//-1이 막고 있으면 채워지지 못한 상태		
		for (int Y = 0; Y < N; Y++) {
			for (int X = 0; X < M; X++) {
				//만약 중간에 0이 있다면
				//채워지지 못한 토마토가 있다는 뜻
				if (map[Y][X]==0) {					
					return -1;
				}
				//그게 아니라 다 채워졌다면
				else {
					if (max<map[Y][X])
						max=map[Y][X];
				}
			}
		}
		return max-1;
	}
}