코딩왕랄프👊🏻

[백준] 7576번 토마토 본문

백준

[백준] 7576번 토마토

hyerm_2 2022. 3. 29. 11:13
반응형
SMALL

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

 

7576번: 토마토

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

www.acmicpc.net

 

 

import java.util.*;
import java.io.*;

public class Main {
  static int m, n;
  static int tomato[][];
  static int maxValue;

  public static void bfs(){
    Queue<Integer> queue_x = new LinkedList<Integer>();
    Queue<Integer> queue_y = new LinkedList<Integer>();
    int dx[] = {-1, 1, 0, 0};
    int dy[] = {0, 0, -1, 1};

    for(int i = 0; i < n; i++){
      for(int j = 0; j < m; j++){
        if(tomato[i][j] == 1 ){
          queue_x.offer(i);
          queue_y.offer(j);
        }
      }
    }

    // queue_x.offer(0);
    // queue_y.offer(0);

    while(!queue_x.isEmpty()){
      int x = queue_x.poll();
      int y = queue_y.poll();
      
      for(int i = 0; i < 4; i++){
        int now_x = x + dx[i];
        int now_y = y + dy[i];
        if(tomato[now_x][now_y] == 0 && now_x >= 0 && now_y >= 0 && now_x < n && now_y < m){
          queue_x.offer(now_x);
          queue_y.offer(now_y);
          tomato[now_x][now_y] = tomato[x][y] + 1;
        }
      }
    }

  }
  
  public static void main(String[] args)  throws NumberFormatException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
    
		m = Integer.parseInt(st.nextToken());
		n = Integer.parseInt(st.nextToken());
		tomato = new int[n][m];
    
		for(int i=0; i<n; i++) {
			st = new StringTokenizer(br.readLine());
			for(int j=0; j<m; j++) {
				tomato[i][j] = Integer.parseInt(st.nextToken());
			}
		}


    bfs();

 }
}
반응형
LIST

'백준' 카테고리의 다른 글

[백준] 1065번 한수  (0) 2022.04.12
[백준] 4673번 셀프 넘버  (0) 2022.04.12
[백준] 2231번 분해합  (0) 2022.04.11
[백준] 11724번 연결요소의 개수  (0) 2022.04.03
[백준] 1260번 DFS와 BFS  (0) 2022.03.26