본문 바로가기
백준 Algorithm/백준 CLASS3

[백준] CLASS3 1012 유기농 배추 - JAVA [자바]

by Echung 2023. 10. 18.

안녕하세요. 이번에는 백준 1012 유기농 배추 문제를 풀어보려고 합니다.

 

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

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 

www.acmicpc.net


Problem

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추 흰 지렁이를 구입하기로 결심한다. 이 지렁이는 배추 근처에 서식하며 해충을 잡아먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추 흰 지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. 한 배추의 상하좌우 네 방향에 다른 배추가 위치한 경우에 서로 인접해 있는 것이다.

한나가 배추를 재배하는 땅은 고르지 못해서 배추를 군데군데 심어 놓았다. 배추들이 모여있는 곳에는 배추흰지렁이가 한 마리만 있으면 되므로 서로 인접해 있는 배추들이 몇 군데에 퍼져있는지 조사하면 총 몇 마리의 지렁이가 필요한지 알 수 있다. 예를 들어 배추밭이 아래와 같이 구성되어 있으면 최소 5마리의 배추 흰 지렁이가 필요하다. 0은 배추가 심어져 있지 않은 땅이고, 1은 배추가 심어져 있는 땅을 나타낸다.

1 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 1 1 0 0 0 1 1 1
0 0 0 0 1 0 0 1 1 1
사진 1. 문제

Solution

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

public class Main {
    
    static int N, M;
    static int[][] board;
    static boolean[][] visited;
    static int count;
    static Queue<Point> queue;
    static int[] dx = {0, -1, 0 ,1};
    static int[] dy = {-1, 0, 1, 0};
    
    static class Point {
        int x, y;
        
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        int T = Integer.parseInt(br.readLine());
        StringTokenizer st;
        while(T-- > 0) {
            count = 0;
            
            st = new StringTokenizer(br.readLine(), " "); 
            M = Integer.parseInt(st.nextToken());
            N = Integer.parseInt(st.nextToken());
            int K = Integer.parseInt(st.nextToken());
            
            board = new int[N][M];
            visited = new boolean[N][M];
            for(int i = 0; i < K; i++) {
                st = new StringTokenizer(br.readLine(), " ");
                int x = Integer.parseInt(st.nextToken());
                int y = Integer.parseInt(st.nextToken());
                
                board[y][x] = 1;
            }
            
            for(int i = 0; i < N; i++) {
                for(int j = 0; j < M; j++) {
                    if(!visited[i][j] && board[i][j] == 1) {
                        count++;
                        bfs(i, j);
                    }
                }    
            }
            
            System.out.println(count);
        }
    }
    
    public static void bfs(int x, int y) {
        queue = new LinkedList<Point>();
        
        queue.offer(new Point(x, y));
        
        while(!queue.isEmpty()) {
            Point p = queue.poll();
            visited[p.x][p.y] = true;
            
            for(int i = 0; i < 4; i++) {
                int nx = dx[i] + p.x;
                int ny = dy[i] + p.y;
            
                if(nx < N && nx >= 0 && ny >= 0 && ny < M) {
                    if(!visited[nx][ny] && board[nx][ny] == 1) {
                        visited[nx][ny] = true;
                        board[nx][ny] = 0;
                        queue.offer(new Point(nx, ny));
                    }
                }
            }
        }
    } 
}

  이번 문제는 BFS(너비 우선 탐색)를 사용하면 쉽게 풀 수 있는 문제이다. 방문을 체크하는 visited와 배추가 심어진 땅 board를 생성하고 visited가 방문 안되어있고, board가 배추가 심어진 땅이면 count를 증가시키고 bfs를 탐색하면 된다.

 

핵심 코드

public static void bfs(int x, int y) {
	queue = new LinkedList<Point>();

	queue.offer(new Point(x, y));
    
    while(!queue.isEmpty()) {
    	Point p = queue.poll();
        visited[p.x][p.y] = true;
        
        for(int i = 0; i < 4; i++) {
        	int nx = dx[i] + p.x;
            int ny = dy[i] + p.y;
            
            if(nx < N && nx >= 0 && ny >= 0 && ny < M) {
				if(!visited[nx][ny] && board[nx][ny] == 1) {
					visited[nx][ny] = true;
					board[nx][ny] = 0;
					queue.offer(new Point(nx, ny));
                }
			}
        }
    }
}

Performance

사진 2. 실행 결과
반응형