BFS - 백준1926 그림

이형석·2024년 2월 6일

알고리즘 Phase1

목록 보기
11/59

42%에서 시간초과 발생함

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

public class Main{
        public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < m; j++) {
                arr[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        // 동서남북배열
        int[] bx = {1, 0, -1, 0};
        int[] by = {0, 1, 0, -1};

        int pictureN = 0;
        int biggest = 0;

        while (true) {
            Pair startPos = null;
            boolean foundPicture = false;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (arr[i][j] == 1) {
                        startPos = new Pair(i, j);
                        foundPicture = true;
                        break;
                    }
                }
                if (foundPicture) {
                    break;
                }
            }
            if (!foundPicture){
                break;
            }
            pictureN++;
            
            Queue<Pair> queue = new LinkedList<>();
            int thisSize = 0;
            // 첫번째주입
            arr[startPos.x][startPos.y] = 0;
            queue.add(startPos);
            thisSize++;

            // while(!empty)
            // queue.pop
            // for(동서남북)
            // if(boundary exception check)
            // if(방문했던곳 or 벽인지)
            // 체크 & push
            while (!queue.isEmpty()) {
                Pair nowPos = queue.poll();
                for (int i = 0; i < 4; i++) {
                    int px = nowPos.x + bx[i];
                    int py = nowPos.y + by[i];

                    if (px < 0 || px > n - 1 || py < 0 || py > m - 1) {
                        continue;
                    }
                    if (arr[px][py] == 1) {
                        queue.add(new Pair(px, py));
                        arr[px][py] = 0;
                        thisSize++;
                    }
                }
            }

            if (thisSize > biggest) {
                biggest = thisSize;
            }
        }
        System.out.println(pictureN);
        System.out.println(biggest);
    }

    static class Pair{
        int x;
        int y;

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

재시도
https://velog.io/@seluo65/BFS-%EB%B0%B1%EC%A4%801926-%EA%B7%B8%EB%A6%BC-%EC%9E%AC%EC%8B%9C%EB%8F%84

profile
금융IT 개발자

0개의 댓글