본문 바로가기

Java/Java 알고리즘 인프런

[Ch.08 - BFS] 04. 토마토

반응형
12. 토마토(BFS 활용)
 

설명

현수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다.

토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.

창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면,

익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다.

하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며,

토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 현수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.

토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때,

며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.

입력

첫 줄에는 상자의 크기를 나타내는 두 정수 M, N이 주어진다. M은 상자의 가로 칸의 수,

N 은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M, N ≤ 1,000 이다.

둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다.

즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다.

하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다.

정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.

출력

여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다.

만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고,

토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.

예시 입력 1 

6 4
0 0 -1 0 0 0
0 0 1 0 -1 0
0 0 -1 0 0 0
0 0 0 0 -1 1

예시 출력 1

4

board[][] : 토마토 위치 배열

dis[][] : 토마토가 익은 날 수 배열

Queue<Point> : 시작 지점부터 익은 토마토 순서 큐

 

#시작 지점이 여러개 일 경우 BFS를 돌기 전에 큐에 넣어 둔다.

  1. 큐에서 꺼내 다음 익은 토마토 설정
  2. 다음 익은 토마토가 익는데 걸리는 날짜 구하기
  3. 큐에서 꺼내서, 다음 큐 시작
    1. 익은 토마토로 시작 지점 설정
    2. 토마토 위치를 입력하면서, 익은 토마토 위치를 큐에 삽입
    3. Level 0 은 0일만에 익는다는 뜻
      1. 날 수 체크 dis[x][y]+1
      2. Level 1은 1일만에 익는다는 뜻
  4. 안익은 토마토 없는지 확인
    1. 처음부터 모두 익은 토마토
      1. 큐에 시작지점으로 모두 존재
      2. dis에 0으로만 존재
      3. 0출력
    2. 익을 수 없는 토마토 존재
      1. board 배열에 0으로 존재
      2. -1출력
    3. 모두 익었을 경우
      1. board 배열에 0없음
      2. dis 배열에서 가장 큰 값 출력

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

class Point {
	int x, y;

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

public class Main {

	// 익은 토마토 1, 익지 않은 토마토 0, 들어있지 않은 칸 -1
	static Queue<Point> q = new LinkedList<Point>();
	static int[][] dis;

	public static void main(String[] args) {
		Scanner kb = new Scanner(System.in);
		int n = kb.nextInt();
		int m = kb.nextInt();
		int[][] board = new int[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				board[i][j] = kb.nextInt();
				if (board[i][j] == 1)
					q.offer(new Point(i, j));
			}
		}
		System.out.println(solution(n, m, board));
	}

	static int solution(int n, int m, int[][] board) {
      if(q.isEmpty()) return -1;
      
		int answer = Integer.MIN_VALUE;
		dis = new int[m][n];
		int cnt = 0;
		int[][] check = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
		while (!q.isEmpty()) {
			Point tmp = q.poll();
			for (int i = 0; i < 4; i++) {
				int nx = tmp.x + check[i][0];
				int ny = tmp.y + check[i][1];
				if (ny >= 0 && nx >= 0 && nx < m && ny < n && board[nx][ny] == 0) {
					q.offer(new Point(nx, ny));
					dis[nx][ny] = dis[tmp.x][tmp.y] + 1;
					board[nx][ny] = 1;
				}
			}
			//q.offer(tmp);
		}
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (board[i][j] == 0)
					return -1;
				answer = Math.max(answer, dis[i][j]);
			}
		}
		return answer;
	}

}

 

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Point {
	public int x, y;

	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
//토마토 BFS
//상자의 크기 가로 M, 세로 N
//익은 토마토 상하좌우의 토마토가 하루 후 익게 된다.
//다 익는데 걸리는 최소 날짜
//익은 토마토 1
//익지 않은 토마토 0
//토마토 없는 칸 -1
// 첫날 부터 모두 익어있으면 0 출력, 모두 익지 못하면 -1 출력
class Main {
	static int[] dx = { -1, 0, 1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static int n, m, answer;
	static int[][] board, dis;
	static Queue<Point> Q = new LinkedList<>();

	public void BFS() {
		while (!Q.isEmpty()) {
			Point tmp = Q.poll();
			for (int i = 0; i < 4; i++) {
				int nx = tmp.x + dx[i];
				int ny = tmp.y + dy[i];
				if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] == 0) {
					board[nx][ny] = 1;
					Q.offer(new Point(nx, ny));
					dis[nx][ny] = dis[tmp.x][tmp.y] + 1;
				}
			}
		}
		for (int i = 0; i < n; i++) {
			System.out.println();
			for (int j = 0; j < m; j++) {
				System.out.print(dis[i][j]+" ");
				
				if(dis[i][j]>0) {
					answer=Math.max(dis[i][j], answer);
				}
				if(board[i][j]==0) {
					answer=-1;
				}
			}
		}

	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		m = kb.nextInt();
		n = kb.nextInt();
		board = new int[n][m];
		dis= new int [n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				board[i][j] = kb.nextInt();
				if (board[i][j] == 1) {
					Q.offer(new Point(i, j));
				}
			}
		}
		T.BFS();
		System.out.println(answer);
	}
}

 

+) 세련된 풀이 [익지 못하는 토마토 있으면 -1 출력]

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Point {
	public int x, y;

	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
//토마토 BFS
//상자의 크기 가로 M, 세로 N
//익은 토마토 상하좌우의 토마토가 하루 후 익게 된다.
//다 익는데 걸리는 최소 날짜
//익은 토마토 1
//익지 않은 토마토 0
//토마토 없는 칸 -1
// 첫날 부터 모두 익어있으면 0 출력, 모두 익지 못하면 -1 출력
class Main {
	static int[] dx = { -1, 0, 1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static int n, m;
	static int[][] board, dis;
	static Queue<Point> Q = new LinkedList<>();

	public void BFS() {
		while (!Q.isEmpty()) {
			Point tmp = Q.poll();
			for (int i = 0; i < 4; i++) {
				int nx = tmp.x + dx[i];
				int ny = tmp.y + dy[i];
				if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] == 0) {
					board[nx][ny] = 1;
					Q.offer(new Point(nx, ny));
					dis[nx][ny] = dis[tmp.x][tmp.y] + 1;
				}
			}
		}
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		m = kb.nextInt();
		n = kb.nextInt();
		board = new int[n][m];
		dis = new int[n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				board[i][j] = kb.nextInt();
				if (board[i][j] == 1)
					Q.offer(new Point(i, j));
			}
		}
		T.BFS();
		boolean flag = true;
		int answer = Integer.MIN_VALUE;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (board[i][j] == 0)
					flag = false;
			}
		}
		if (flag) {
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					answer = Math.max(answer, dis[i][j]);
				}
			}
			System.out.println(answer);
		} else
			System.out.println(-1);
	}
}

 

+) 세련된 풀이2 [메서드 이용하면 타임리밋 걸림]

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Point{
  public int x, y;
  Point(int x, int y){
    this.x=x;
    this.y=y;
  }
  public boolean inValid(int n, int m){
    if(x >= 0 && x < n && y >= 0 && y < m) return true;
    return false;
  }
}
//토마토 BFS
//상자의 크기 가로 M, 세로 N
//익은 토마토 상하좌우의 토마토가 하루 후 익게 된다.
//다 익는데 걸리는 최소 날짜
//익은 토마토 1
//익지 않은 토마토 0
//토마토 없는 칸 -1
// 첫날 부터 모두 익어있으면 0 출력, 모두 익지 못하면 -1 출력
class Main {

	static int n, m;
	static int[][] board, dis;
	static Queue<Point> Q = new LinkedList<>();

	public void BFS() {
		while(!Q.isEmpty()){
      Point tmp=Q.poll();
      final int[][] check ={{-1,0}, {0,-1}, {0,1}, {1,0}};
      for(int i=0;i<4;i++){
        Point moved=new Point(tmp.x+check[i][0], tmp.y+check[i][1]);
       	 if (moved.x >= 0 && moved.x < n && moved.y >= 0 && moved.y < m && board[moved.x][moved.y] == 0) {
//       if (moved.x < 0 || moved.x >= n || moved.y < 0 || moved.y >= m || board[moved.x][moved.y] != 0)continue;
//     	 if (moved.inValid(n,m) && board[moved.x][moved.y] == 0) {
        
            board[moved.x][moved.y]=1;
            Q.offer(moved);
            dis[moved.x][moved.y]=dis[tmp.x][tmp.y]+1;
         }
        }
      }
    }
	

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		m = kb.nextInt();
		n = kb.nextInt();
		board = new int[n][m];
		dis = new int[n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				board[i][j] = kb.nextInt();
				if (board[i][j] == 1)
					Q.offer(new Point(i, j));
			}
		}
		T.BFS();
		boolean flag = true;
		int answer = Integer.MIN_VALUE;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (board[i][j] == 0)
					flag = false;
			}
		}
		if (flag) {
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					answer = Math.max(answer, dis[i][j]);
				}
			}
			System.out.println(answer);
		} else
			System.out.println(-1);
	}
}

 

 

 

(1) 토마토 위치와 이동 가능 위치 확인하기 위한 메서드를 작성한 클래스

(2) 큐에 익은 토마토 삽입 후, BFS를 돌린다.

(3) BFS에서는 큐에서 하나씩 빼면서 확인

1. 이동가능한 위치이면

2. 익은 토마토로 변경

3. 익은 날짜 입력

4. 익은 토마토 큐에 넣기

 

(4) BFS가 끝나면, 모두 익었는지 확인하는 메서드 작성

(5) 다 익었을 경우 날짜 배열에서 가장 큰 값을 반환

(6) 다 안 익었을 경우 -1 반환

import java.util.*;
class Pos{
  public int x,y;
  Pos(int x, int y){
    this.x=x;
    this.y=y;
  }
  public boolean isValid(int width, int height){
    if(x<0||x>=width||y<0||y>=height){
      return false;
    }
    return true;
  }

}
public class Main {
  static int answer, n, m, L;
  static int[][] arr;
  static Queue<Pos> q = new LinkedList<>();
  static final int[][] dis= {{0,1},{0,-1},{1,0},{-1,0}};
  static int[][] count;
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    m = in.nextInt();
    n = in.nextInt();
    arr = new int[n][m];
    count=new int[n][m];
    for(int i=0;i<n;i++){
      for(int j=0;j<m;j++){
        arr[i][j]=in.nextInt();
        if(arr[i][j]==1){
          q.offer(new Pos(i,j));
        }
      }
    }
    DFS();
    boolean flag = true;
		int answer = Integer.MIN_VALUE;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (arr[i][j] == 0)
					flag = false;
			}
	}
    if(flag){ 
      int max=Integer.MIN_VALUE;
      for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
          max=Math.max(count[i][j],max);
        }
      }
      System.out.println(max);
    }
    else System.out.println(-1);
  }
  //익었는지 체크하는 함수
  //BFS - 토마토가 전부 익는데 걸리는 최소 시간
  static void DFS(){
    while(!q.isEmpty()){
      Pos p = q.poll();
        for(int i=0;i<4;i++){
          Pos ns=new Pos(p.x+dis[i][0], p.y+dis[i][1]);
          if(ns.isValid(n,m)&&arr[ns.x][ns.y]==0){
            arr[ns.x][ns.y]=1;
            q.offer(ns);
            count[ns.x][ns.y]=count[p.x][p.y]+1;
        } 
      } 
    }   
  }
}
반응형