Home [BOJ 1926] 그림
Post
Cancel

[BOJ 1926] 그림

그림 (1926번)

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

풀이방법

  1. Queue를 이용해 방문하지 않았으면서 해당 위치의 값이 1인 좌표를 추가한다.
  2. 현재 위치가 방문하지 않았고 1이라면 넓이를 1 증가시킨 후 Queue에 넣는다.
  3. pollQueue에 있는 값을 가져와 상하좌우 비교한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

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 y = Integer.parseInt(st.nextToken());
        int x = Integer.parseInt(st.nextToken());

        int[][] paper = new int[y][x];
        boolean[][] visited = new boolean[y][x];

        int[] directX = {1, 0, -1, 0};
        int[] directY = {0, 1, 0, -1};

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

        Queue<int[]> queue = new LinkedList<>();
        int dx = 0;
        int dy = 0;
        int curX = 0;
        int curY = 0;
        int countOfPicture = 0;
        int maxAreaOfPicture = 0;
        int areaOfPicture = 0;
        for(int i=0; i<y; i++) {
            for(int j=0; j<x; j++) {
                if (visited[i][j] || paper[i][j] == 0) continue;
                queue.add(new int[]{i, j});
                visited[i][j] = true;
                countOfPicture++;

                while (!queue.isEmpty()) {
                    areaOfPicture++;
                    int[] pos = queue.poll();
                    curX = pos[1]; curY = pos[0];

                    for(int k=0; k<4; k++) {
                        dx = curX + directX[k];
                        dy = curY + directY[k];

                        if (dx < 0 || dx >= x || dy < 0 || dy >= y) continue;
                        if (visited[dy][dx] || paper[dy][dx] != 1) continue;

                        queue.add(new int[]{dy, dx});
                        visited[dy][dx] = true;
                    }
                }

                maxAreaOfPicture = Math.max(maxAreaOfPicture, areaOfPicture);
                areaOfPicture = 0;
            }
        }

        System.out.println(countOfPicture);
        System.out.println(maxAreaOfPicture);
    }
}

This post is licensed under CC BY 4.0 by the author.

[BOJ 10773] 제로

[BOJ 2178] 미로 탐색

Comments powered by Disqus.