[Java] 백준 1236번 [성 지키기] 자바

: ) YOUNG·2021년 11월 3일
2

알고리즘

목록 보기
6/370
post-thumbnail

백준 1236번
https://www.acmicpc.net/problem/1236

문제

영식이는 직사각형 모양의 성을 가지고 있다. 성의 1층은 몇 명의 경비원에 의해서 보호되고 있다. 영식이는 모든 행과 모든 열에 한 명 이상의 경비원이 있으면 좋겠다고 생각했다.

성의 크기와 경비원이 어디있는지 주어졌을 때, 몇 명의 경비원을 최소로 추가해야 영식이를 만족시키는지 구하는 프로그램을 작성하시오.


입력

첫째 줄에 추가해야 하는 경비원의 최솟값을 출력한다.


생각하기


코드

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

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 col_sum = 0;
        int row_sum = 0;
       
        boolean[][] arr = new boolean[N][M];

        for(int i=0; i<N; i++) {
            String str = br.readLine();
            for(int j=0; j<M; j++) {
           
                if(str.charAt(j) == '.') {
                    arr[i][j] = false;
                }
                else {
                    arr[i][j] = true;
                }
            }
        }
       
        // 열검사
        for(int i=0; i<M; i++) {
            int count = 0;

            for(int k=0; k<N; k++) {
                if(arr[k][i] == false) {
                    count ++;
                }            
            }

            if(count == N) {
                //열에 필요한 경비원 수
                col_sum++;
            }
        }

        for(int i=0; i<N; i++) {
            int count = 0;
            for(int k=0; k<M; k++) {
                if(arr[i][k] == false) {
                    count ++;
                }                 
            }

            if(count == M) {
                // 행에 필요한 경비원 수
                row_sum++;
            }
        }

        if(row_sum >= col_sum) {
            System.out.println(row_sum);
        }
        else {
            System.out.println(col_sum);
        }        
    }
}

0개의 댓글