카테고리 없음

백준 1012 유기농 배추

miffy짱 2022. 11. 27. 14:10
반응형

백준 1012 유기농 배추


  • 이번 문제에서는 자바로 가장일반적인 bfs 문제를 풀어보았다. Pair 클래스를 만들어 좌표를 기록하는 용도로 사용하였다. 다만, 하나의 클래스 안에서 다 해결하려다 보니 코드가 너무 길어지고 가독성도 떨어지게 되었는데, 이를 메소드로 분리할 수 있다면 더 좋을 것 같다.

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

public class Boj_1012 {


    public static void main(String[] args) {
        int t,m,n,k;
        Scanner scanner = new Scanner(System.in);
        t = scanner.nextInt();

        for (int i = 0; i < t; i++) {
            List<Integer> x_dir = List.of(1, 0, -1, 0);
            List<Integer> y_dir = List.of(0, 1, 0, -1);
            m = scanner.nextInt();
            n = scanner.nextInt();
            k = scanner.nextInt();
            int[][] table = new int[50][50];
            int[][] visited = new int[50][50];
            Queue<Pair> q = new LinkedList<>();
            int cnt = 0;

            for (int j = 0; j < k; j++) {
                int tmp1 = scanner.nextInt();
                int tmp2 = scanner.nextInt();
                table[tmp1][tmp2] = 1;
            }

            //dfs 시작
            for (int garo = 0; garo < m; garo++) {
                for (int sero = 0; sero < n; sero++) {
                    if (table[garo][sero] == 1 && visited[garo][sero] == 0) {
                        cnt++;
                        q.add(new Pair(garo, sero));
                        visited[garo][sero] = 1;
                        //cnt++;
                        while (!q.isEmpty()) {
                            Pair cur = q.peek();
                            q.remove();
                            for (int dir = 0; dir < 4; dir++) {
                                int nx = cur.x + x_dir.get(dir);
                                int ny = cur.y + y_dir.get(dir);
                                if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
                                if (visited[nx][ny] == 1 || table[nx][ny] != 1) continue;
                                visited[nx][ny]  = 1;
                                //cnt++;
                                q.add(new Pair(nx, ny));
                            }
                        }
                    }
                }
            }
            System.out.println(cnt);
        }

    }

    public static class Pair {
        int x,y;

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

    }
}
  • java 에서 큐 사용 법
 Queue<Pair> q = new LinkedList<>();
                         q.add(new Pair(garo, sero));
                        while (!q.isEmpty()) {
                            Pair cur = q.peek();
                            q.remove();

다음처럼, 자바에서 큐 등 자료구조의 사용문법이 기존 pop, push 등과 이름이 달라서 좀 헷갈렸지만, ide의 자동완성으로 편하게 할 수 있었다. 슬슬 외우면서 하면 될 것 같다.