반응형

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

 

7682번: 틱택토

틱택토 게임은 두 명의 사람이 번갈아가며 말을 놓는 게임이다. 게임판은 3×3 격자판이며, 처음에는 비어 있다. 두 사람은 각각 X 또는 O 말을 번갈아가며 놓는데, 반드시 첫 번째 사람이 X를 놓고

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 백트래킹을 이용하여 가능한 모든 경우의 수를 map에 저장합니다.

 

2. 결과를 입력받고 map에 있는지 체크한 후 있다면 valid, 없다면 invalid를 출력해줍니다.

 

[ 소스코드 ]

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<string>
#include<cstring>
#include<unordered_map>
 
using namespace std;
 
char tik[10];
char temp[10= ".........";
unordered_map<stringbool> m;
 
void dfs(int level) 
{
    if (level == 9) {
        m[temp] = true;    //승부가 나지 않았을 때
        return;
    }
 
    for (int i = 0; i < 3; i++) {
        if (temp[i * 3== temp[i * 3 + 1&& temp[i * 3 + 1== temp[i * 3 + 2]&&temp[i*3!= '.') {    //가로
            m[temp] = true;
            return;
        }
        if (temp[i] == temp[i + 3&& temp[i + 3== temp[i + 6]&&temp[i] != '.') {    //세로
            m[temp] = true;
            return;
        }
    }
    if (((temp[0== temp[4&& temp[4== temp[8]) || (temp[2== temp[4&& temp[4== temp[6])) && temp[4!= '.') {    //대각
        m[temp] = true;
        return;
    }
 
    for (int i = 0; i < 9; i++) {
        if (temp[i] == '.') {
            if (level % 2 == 0) {
                temp[i] = 'X';
                dfs(level + 1);
                temp[i] = '.';
            }
            else {
                temp[i] = 'O';
                dfs(level + 1);
                temp[i] = '.';
            }
        }
    }
}
 
int main()
{
    dfs(0);    //가능한 경우의수 map에 저장
 
    while (1) {
        scanf("%s"&tik);
        if (!strcmp(tik, "end")) {
            return 0;
        }
 
        if (m[tik] == true) {
            printf("valid\n");
        }
        else {
            printf("invalid\n");
        }
    }
}
cs
반응형

+ Recent posts