작성일 :

문제 링크

5239번 - Chess Puzzle

설명

여러 개의 룩이 놓인 체스판이 주어질 때, 서로를 공격하는 룩이 있는지 판별하는 문제입니다.


접근법

룩은 같은 행이나 같은 열에 다른 룩이 있으면 서로 공격할 수 있습니다.

따라서 각 체스판마다 이미 사용한 행과 열을 따로 기록하면 됩니다. 어떤 룩의 행이나 열이 이전에 나온 적이 있으면 바로 NOT SAFE이고, 끝까지 겹치지 않으면 SAFE입니다.

체스판 크기가 8 x 8이라서 배열로 간단하게 처리할 수 있습니다.



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

class Program {
  static void Main() {
    int t = int.Parse(Console.ReadLine()!);

    for (int tc = 0; tc < t; tc++) {
      int[] input = Console.ReadLine()!.Split().Select(int.Parse).ToArray();
      int rooks = input[0];

      bool[] cols = new bool[9];
      bool[] rows = new bool[9];
      bool safe = true;

      for (int i = 0; i < rooks; i++) {
        int col = input[1 + 2 * i];
        int row = input[2 + 2 * i];

        if (cols[col] || rows[row])
          safe = false;

        cols[col] = true;
        rows[row] = true;
      }

      Console.WriteLine(safe ? "SAFE" : "NOT SAFE");
    }
  }
}

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;

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

  int t;
  cin >> t;

  while (t--) {
    int rooks;
    cin >> rooks;

    bool cols[9] = {};
    bool rows[9] = {};
    bool safe = true;

    for (int i = 0; i < rooks; i++) {
      int col, row;
      cin >> col >> row;

      if (cols[col] || rows[row])
        safe = false;

      cols[col] = true;
      rows[row] = true;
    }

    cout << (safe ? "SAFE" : "NOT SAFE") << "\n";
  }

  return 0;
}

Tags: 5239, BOJ, C#, C++, 구현, 백준, 알고리즘

Categories: ,