알고리즘 문제 풀이/BOJ

[beakjoon]7682 틱택토 java

v 2022. 4. 6. 18:00
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
68
69
70
import java.io.*;
import java.util.*;
 
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String cur = br.readLine();
        while (!("end").equals(cur)) {
            if (tictactoc(cur)) {
                System.out.println("valid");
            } else {
                System.out.println("invalid");
            }
            cur = br.readLine();
        }
    }
 
    private static boolean tictactoc(String cur) {
        int x = 0;
        int o = 0;
 
        for (char c : cur.toCharArray()) {
            if (c == 'X')
                x++;
            else if (c == 'O')
                o++;
        }
        if (x == 5 && o == 4) {
            if (verify(cur, 'O'&& !verify(cur, 'X')) {
                return false;
            } else if (verify(cur, 'O'&& verify(cur, 'X')) {
                return false;
            }
            return true;
        } else if (x == o + 1) {
            if (verify(cur, 'X'&& !verify(cur, 'O')) {
                return true;
            }
        } else if (x == o) {
            if (verify(cur, 'O'&& !verify(cur, 'X')) {
                return true;
            }
        }
        return false;
    }
 
    static boolean verify(String cur, char type) {
        for (int i = 0; i < 3; i++) {
            int row = 0;
            int col = 0;
            for (int j = 0; j < 3; j++) {
                int colIdx = 3 * i + j;
                int rowIdx = 3 * j + i;
                if (cur.charAt(rowIdx) == type)
                    row++;
                if (cur.charAt(colIdx) == type)
                    col++;
            }
            if (row == 3)
                return true;
            if (col == 3)
                return true;
        }
        if (cur.charAt(0== type && cur.charAt(4== type && cur.charAt(8== type)
            return true;
        if (cur.charAt(2== type && cur.charAt(4== type && cur.charAt(6== type)
            return true;
        return false;
    }
}
cs
반응형