작성일 :

문제 링크

1236번 - 성 지키기

설명

성의 모든 행과 열에 최소 한 명의 경비원이 있어야 합니다.

현재 배치에서 추가로 필요한 최소 경비원 수를 구하는 문제입니다.


접근법

먼저, 각 행과 열에 경비원이 있는지 확인합니다. 입력을 순회하며 경비원이 있는 행과 열을 표시합니다.

다음으로, 경비원이 없는 행의 개수와 열의 개수를 각각 셉니다. 한 명의 경비원을 배치하면 한 행과 한 열을 동시에 커버할 수 있으므로, 두 값 중 큰 값이 필요한 최소 인원입니다.


Code

C#

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
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var first = Console.ReadLine()!.Split();
      var R = int.Parse(first[0]);
      var C = int.Parse(first[1]);
      var rowHas = new bool[R];
      var colHas = new bool[C];

      for (var r = 0; r < R; r++) {
        var line = Console.ReadLine()!;
        for (var c = 0; c < C; c++) {
          if (line[c] == 'X') {
            rowHas[r] = true;
            colHas[c] = true;
          }
        }
      }

      var needRow = 0;
      var needCol = 0;
      for (var r = 0; r < R; r++)
        if (!rowHas[r])
          needRow++;
      for (var c = 0; c < C; c++)
        if (!colHas[c])
          needCol++;

      Console.WriteLine(Math.Max(needRow, needCol));
    }
  }
}

C++

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
#include <bits/stdc++.h>
using namespace std;

typedef vector<bool> vb;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int R, C; cin >> R >> C;
  vb rowHas(R, false), colHas(C, false);

  for (int r = 0; r < R; r++) {
    string line; cin >> line;
    for (int c = 0; c < C; c++) {
      if (line[c] == 'X') {
        rowHas[r] = true;
        colHas[c] = true;
      }
    }
  }

  int needRow = 0, needCol = 0;
  for (bool v : rowHas)
    if (!v)
      needRow++;
  for (bool v : colHas)
    if (!v)
      needCol++;

  cout << max(needRow, needCol) << "\n";

  return 0;
}