PS/백준

[백준] 영상처리 21938

팡세영 2022. 11. 11. 17:44

1 0 1
0 1 0
1 0 1


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

 

21938번: 영상처리

화면의 세로 $N$, 가로 $M$ 값이 공백으로 구분되어 주어진다. 두 번째 줄부터 $N + 1$줄까지 $i$번째 가로를 구성하고 있는 픽셀의 $R_{i,j}$, $G_{i,j}$, $B_{i,j}$의 값이 공백으로 구분되어 총 $M$개 주어진

www.acmicpc.net


[예제입력 1]

 

예제 입력 1을 3x3으로 변경하면 아래와 같이 됩니다.

1 0 1
0 1 0
1 0 1

  • R, G, B 의 평균 값을 구해서 경계 값이 넘으면 255로 넘지 않으면 0으로 배열을 초기화 시켜준 후
  • bfs로 상하좌우 탐색을 해서 인접한 구역의 수를 구하면 된다.

[Java]

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main
{
    public static int dx[] = {0, 0, -1, 1};
    public static int dy[] = {-1, 1, 0, 0};
    public static int n, m;
    public static int arr[][];
    public static boolean visited[][];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());

        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
        arr = new int[n][m];
        visited = new boolean[n][m];

        for(int i=0; i<n; i++){
            st = new StringTokenizer(br.readLine());

            for(int j=0; j<m; j++){
                int r = Integer.parseInt(st.nextToken());
                int g = Integer.parseInt(st.nextToken());
                int b = Integer.parseInt(st.nextToken());
                arr[i][j] = (r+g+b) / 3;
            }
        }

        int t = Integer.parseInt(br.readLine());

        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(t <= arr[i][j]) arr[i][j] = 255;
                else arr[i][j] = 0;
            }
        }

        int ans = 0;
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(arr[i][j] == 255 && !visited[i][j]){
                    ans++;
                    bfs(new Pos(j, i));
                }
            }
        }

        bw.write(ans + "");
        bw.flush();
    }

    public static void bfs(Pos start){
        Queue<Pos> q = new LinkedList<>();
        q.add(start);
        visited[start.y][start.x] = true;

        while(!q.isEmpty()){
            Pos cur = q.poll();

            for(int i=0; i<4; i++){
                int nx = cur.x + dx[i];
                int ny = cur.y + dy[i];

                if(check(nx, ny)) continue;

                visited[ny][nx] = true;
                q.add(new Pos(nx, ny));

            }
        }
    }

    public static boolean check(int nx, int ny){
        return (nx >= m || nx < 0 || ny >= n || ny < 0 ||
                visited[ny][nx] || arr[ny][nx] == 0) ? true : false;
    }
}

class Pos{
    int x, y;

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