ALGORITHM/BOJ

[백준] 14716 현수막

0298 2021. 11. 15. 22:07

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

 

14716번: 현수막

혁진이의 생각대로 프로그램을 구현했을 때, 현수막에서 글자의 개수가 몇 개인지 출력하여라.

www.acmicpc.net

2021-11-13


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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main14716 {
    public static int N, M, answer;
    public static int[][] arr;
    public static int[] dx = {-1010-1-111};
    public static int[] dy = {0-101-11-11};
    public static boolean[][] vtd;
    public static void solve(int valx, int valy) {
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{valx, valy});
        vtd[valx][valy] = true;
 
        while(!q.isEmpty()) {
            int size = q.size();
            while(size > 0) {
                int[] tmp = q.poll();
                int x = tmp[0];
                int y = tmp[1];
 
                for(int i = 0; i < 8; i++) {
                    int nx = x + dx[i];
                    int ny = y + dy[i];
 
                    if(nx < 0 || ny < 0 || nx >= N || ny >= M || arr[nx][ny] == 0 || vtd[nx][ny]) continue;
                    else {
                        vtd[nx][ny] = true;
                        q.add(new int[]{nx, ny});
                    }
                 }
                size--;
            }
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(bf.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        answer = 0;
        arr = new int[N][M];
        vtd = new boolean[N][M];
 
        for(int i = 0; i < N; i++) {
            st = new StringTokenizer(bf.readLine());
            for(int j = 0; j < M; j++) {
                arr[i][j] = Integer.parseInt(st.nextToken());
            }
        }
 
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < M; j++) {
                if(arr[i][j] == 1 && !vtd[i][j]) {
                    solve(i, j);
                    answer++;
                }
            }
        }
 
        System.out.println(answer);
    }
}
cs

#문제풀이

BFS 문제인데 대각선 방향까지 체크하면 된다.