작성일 :

문제 링크

32370번 - Rook

설명

룩이 (0,0)에서 시작해 상대의 말 A를 잡을 때 필요한 최소 이동 횟수를 구하는 문제입니다.


접근법

목표가 시작점과 같은 행이나 열에 있으면, 그 사이에 아군 말이 있는지만 보면 됩니다. 막히지 않으면 한 번, 막히면 돌아가야 해서 세 번입니다.
목표가 같은 행·열이 아니면 두 번이면 충분합니다. 한 번 꺾는 경로가 두 가지인데, 아군 말이 한 경로를 막아도 다른 경로는 남기 때문입니다.


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

class Program {
  static void Main() {
    var p1 = Console.ReadLine()!.Split();
    var a = int.Parse(p1[0]);
    var b = int.Parse(p1[1]);
    var p2 = Console.ReadLine()!.Split();
    var x = int.Parse(p2[0]);
    var y = int.Parse(p2[1]);

    int ans;
    if (a == 0) {
      if (x == 0 && y > 0 && y < b) ans = 3;
      else ans = 1;
    } else if (b == 0) {
      if (y == 0 && x > 0 && x < a) ans = 3;
      else ans = 1;
    } else ans = 2;

    Console.WriteLine(ans);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;

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

  int a, b; cin >> a >> b;
  int x, y; cin >> x >> y;
  int ans;

  if (a == 0) {
    if (x == 0 && y > 0 && y < b) ans = 3;
    else ans = 1;
  } else if (b == 0) {
    if (y == 0 && x > 0 && x < a) ans = 3;
    else ans = 1;
  } else ans = 2;

  cout << ans << "\n";

  return 0;
}