작성일 :

문제 링크

12759번 - 틱! 택! 토!

설명

3 x 3 크기의 틱택토 보드에서, 입력된 좌표에 따라 게임을 진행하며 승자를 판단하는 문제입니다.

게임은 다음과 같은 규칙을 따릅니다:

  • 두 플레이어가 번갈아가며 1 또는 2로 표시된 마커를 놓습니다.
  • 먼저 가로, 세로, 혹은 대각선 중 하나에서 마커 3개를 연속으로 놓은 플레이어가 승리합니다.
  • 승자가 발생한 이후에도 입력은 계속 주어질 수 있지만, 게임은 즉시 종료되어야 합니다.
  • 모든 칸이 채워졌음에도 승자가 없다면 무승부입니다.

입력은 항상 유효한 게임 진행이 보장되며, 중복 좌표나 잘못된 입력은 주어지지 않습니다.


접근법

게임은 총 9번의 턴 안에 끝나며, 각 턴마다 플레이어가 번갈아가며 위치를 선택합니다.

각 입력 좌표에 따라 해당 위치를 기록하고, 매 턴마다 현재 플레이어가 승리 조건을 만족하는지를 확인합니다.

승리 조건은 다음과 같습니다:

  • 가로 또는 세로 한 줄이 같은 플레이어로 모두 채워졌을 때
  • 또는 좌상우하 대각선 ↘ 혹은 우상좌하 대각선↙이 모두 같은 플레이어로 채워졌을 때


이 조건을 충족하는 순간 해당 플레이어가 즉시 승리하며, 더 이상 경기는 진행되지 않습니다.

모든 입력이 종료될 때까지도 승리 조건이 만족되지 않으면 무승부로 간주하고 0을 출력합니다.



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
35
36
37
using System;

class Program {
  static int[,] board = new int[3, 3];

  static bool IsWon(int player) {
    for (int i = 0; i < 3; i++) {
      if ((board[i, 0] == player && board[i, 1] == player && board[i, 2] == player) ||
          (board[0, i] == player && board[1, i] == player && board[2, i] == player))
        return true;
    }
    return (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player) ||
           (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player);
  }

  static void Main() {
    int player = int.Parse(Console.ReadLine());
    bool finished = false;

    for (int i = 0; i < 9; i++) {
      var tokens = Console.ReadLine().Split();
      int x = int.Parse(tokens[0]) - 1;
      int y = int.Parse(tokens[1]) - 1;

      board[x, y] = player;

      if (!finished && IsWon(player)) {
        Console.WriteLine(player);
        finished = true;
      }

      player = 3 - player;
    }

    if (!finished) Console.WriteLine(0);
  }
}

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

int table[3][3];

bool isWon(int player) {
  for (int i = 0; i < 3; i++) {
    if ((table[i][0] == player && table[i][1] == player && table[i][2] == player) ||
        (table[0][i] == player && table[1][i] == player && table[2][i] == player))
      return true;
  }

  return (table[0][0] == player && table[1][1] == player && table[2][2] == player) ||
         (table[0][2] == player && table[1][1] == player && table[2][0] == player);
}

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

  int player; cin >> player;
  bool won = false;

  for (int i = 0; i < 9; i++) {
    int x, y; cin >> x >> y;
    table[x-1][y-1] = player;

    if (!won && isWon(player)) {
      cout << player << "\n";
      won = true;
    }

    player = 3 - player;
  }

  if (!won) cout << "0\n";

  return 0;
}