티스토리 뷰

알고리즘

[백준] 7682. 틱택토 (Java)

melthleeth 2021. 9. 16. 15:16

풀이

 

 

7682번: 틱택토

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 줄은 9개의 문자를 포함하며, 'X', 'O', '.' 중 하나이다. '.'은 빈칸을 의미하며, 9개의 문자는 게임판에서 제일 윗 줄 왼쪽부터의 순서이다. 입

www.acmicpc.net

 

 

X빙고, O빙고 둘 다 존재할 경우 invalid인걸 놓쳐서 헤메고 있었음

 

  • 논리적으로 되는 경우, 안되는 경우를 다 따져야 하는 문제!! 알고리즘같지 않은(?) 문제였다.
  • 맨처음에 입력받은 String에서 O의 개수, X의 개수를 센다.
  • 가로, 세로, 대각선 경우를 보면서 빙고일 때 O 빙고의 수, X 빙고의 수도 센다.
  1. X 빙고의 수 > 0일 때
    • O 빙고의 수 > 0이면 이미 X 빙고가 나왔을 때 게임이 종료되었어야 하는데 아닌 경우이므로 invaild
    • X의 개수 - O의 개수 = 1일때만 valid
  2. O 빙고의 수 > 0일 때 X의 개수 - O의 개수 = 0일때만 valid
  3. 1, 2에 해당하지 않는 경우 X의 개수 + O의 개수 = 9일때만 valid

 

 

 

코드

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        String str = "";
        while (!(str = br.readLine()).equals("end")) {

            String ans = isValid(str) ? "valid" : "invalid";
            bw.write(ans);
            bw.newLine();
        }

        br.close();
        bw.close();
    }

    public static boolean isValid(String str) {
        int cntO = 0, cntX = 0, ansO = 0, ansX = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == 'O') cntO++;
            else if (str.charAt(i) == 'X') cntX++;
        }

        if (cntX - cntO != 1 && cntX - cntO != 0) return false;

        for (int i = 0; i < 9; i += 3) {
            if (str.charAt(i) == '.') continue;
            if (str.charAt(i) == str.charAt(i + 1) && str.charAt(i + 1) == str.charAt(i + 2)) {
                if (str.charAt(i) == 'X') ansX++;
                else ansO++;
            }
        }

        for (int j = 0; j < 3; j++) {
            if (str.charAt(j) == '.') continue;
            if (str.charAt(j) == str.charAt(j + 3) && str.charAt(j + 3) == str.charAt(j + 6)) {
                if (str.charAt(j) == 'X') ansX++;
                else ansO++;
            }
        }

        if (str.charAt(4) != '.') {
            if ((str.charAt(4) == str.charAt(0) && str.charAt(4) == str.charAt(8))
                    || (str.charAt(4) == str.charAt(2) && str.charAt(4) == str.charAt(6))) {
                if (str.charAt(4) == 'X') ansX++;
                else ansO++;
            }
        }

        if (ansX > 0) {
            if (ansO > 0) return false;
            if (cntX - cntO == 1) return true;
            else return false;
        }
        if (ansO > 0) {
            if (cntX - cntO == 0) return true;
            else return false;
        }
        if (cntX + cntO == 9) return true;
        return false;
    }
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함