[BaekJoon] 1236 성 지키기 (java)

SeongWon Oh·2021년 10월 3일
0
post-thumbnail

🔗 문제 링크

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


👨🏻‍💻 작성한 코드

package backjoon;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class B1236 {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		int row = Integer.parseInt(st.nextToken());
		int column = Integer.parseInt(st.nextToken());
		
		
		// 성 정보를 배열로 생성
		boolean[][] arr = new boolean[row][column];
		String[] temp = new String[column];
		for (int i=0; i<row; i++) {
			temp = br.readLine().split("");
			
			for (int j=0; j<column; j++) {
				if (temp[j].equals("X")) arr[i][j] = true;
			}
		}
		
		int notRowGuard = 0; // 가드가 없는 row의 수
		int notColumnGuard = 0; // 가드가 없는 column의 수
		boolean hasGuard;
		// Guard가 없는 Row 체크
		for (int i=0; i< row; i++) {
			hasGuard = false;
			for (int j=0; j<column; j++) {
				if (arr[i][j]) { // 가드가 해당 라인에 존재하면 해당 줄은 탐색 종료
					hasGuard = true;
					break;
				}
			}
			if (!hasGuard) notRowGuard++;
		}
		
		// Guard가 없는 Column 체크
		for (int i=0; i< column; i++) {
			hasGuard = false;
			for (int j=0; j<row; j++) {
				if (arr[j][i]) { // 가드가 해당 라인에 존재하면 해당 줄은 탐색 종료
					hasGuard = true;
					break;
				}
			}
			if (!hasGuard) notColumnGuard++;
		}
		
		// guard가 없는 line이 더 많은 값 출력
		System.out.println(notRowGuard>notColumnGuard ? notRowGuard:notColumnGuard);
	}
}


📝 코드 설명

나의 문제풀이는 문제에서 주어지는 크기의 배열을 생성한 다음 각각의 위치에 가드의 유무를 기록한 후 반복문을 통해 탐색을 하며 가드가 없는 column, row가 각각 몇명이 있는지 카운트 하였다.

최종 답인 추가로 필요한 가드의 수는 가드가 없는 row와 column의 수 중에서 큰 값이 답이 된다. 그 이유는 아래의 그림과 같이 가드가 없는 row, column의 경우 만나는 지점이 있는데 그 위치에 가드를 배치하면 한명의 가드를 설치하였으나 가드가 없는 row, column이 둘 다 하나씩 줄일 수 있다.

이러한 이유 때문에 필요한 가드는 가드가 없는 row와 column의 수 중에서 큰 값만큼 필요하다.

profile
블로그 이전했습니다. -> https://seongwon.dev/

0개의 댓글