Problem Solving/Baekjoon

[백준] 1895 필터 - Brute Force / Java

graycode 2023. 9. 4. 22:11

 문제 링크

 

1895번: 필터

숫자 9개가 오름차순이나 내림차순으로 정렬되어 있을 때, 중앙값은 다섯 번째 숫자이다. 예를 들어, 1, 3, 4, 1, 2, 6, 8, 4, 10의 중앙값은 4이다. (1 ≤ 1 ≤ 2 ≤ 3 ≤ 4 ≤ 4 ≤ 6 ≤ 8 ≤ 10) 이미지 I는

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static int[][] mat;

    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());

        int r = Integer.parseInt(st.nextToken()), c = Integer.parseInt(st.nextToken());

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

        int t = Integer.parseInt(br.readLine()), cnt = 0;
        for (int i = 0; i < r - 2; i++) for (int j = 0; j < c - 2; j++) if (t <= getMedian(i, j)) cnt++;

        bw.write(String.valueOf(cnt));
        bw.flush();
    }

    private static int getMedian(int y, int x) {
        int[] arr = new int[9];

        int idx = 0;
        for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) arr[idx++] = mat[i + y][j + x];

        Arrays.sort(arr);
        return arr[4];
    }

}