티스토리 뷰
풀이
7682번: 틱택토
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 줄은 9개의 문자를 포함하며, 'X', 'O', '.' 중 하나이다. '.'은 빈칸을 의미하며, 9개의 문자는 게임판에서 제일 윗 줄 왼쪽부터의 순서이다. 입
www.acmicpc.net
X
빙고,O
빙고 둘 다 존재할 경우invalid
인걸 놓쳐서 헤메고 있었음
- 논리적으로 되는 경우, 안되는 경우를 다 따져야 하는 문제!! 알고리즘같지 않은(?) 문제였다.
- 맨처음에 입력받은 String에서
O
의 개수,X
의 개수를 센다. - 가로, 세로, 대각선 경우를 보면서 빙고일 때
O 빙고
의 수,X 빙고
의 수도 센다.
X 빙고의 수 > 0
일 때O 빙고의 수 > 0
이면 이미 X 빙고가 나왔을 때 게임이 종료되었어야 하는데 아닌 경우이므로invaild
X의 개수
-O의 개수
= 1일때만valid
O 빙고의 수 > 0
일 때X의 개수
-O의 개수
= 0일때만valid
- 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;
}
}
'알고리즘' 카테고리의 다른 글
[백준] 10814. 나이순 정렬 (Java) (0) | 2021.10.08 |
---|---|
[프로그래머스] 문자열 압축 (Java) (0) | 2021.10.07 |
문자열 문제풀이에 유용한 replaceAll(), matches() (ft. 정규표현식) (0) | 2021.09.09 |
[백준] 1107. 리모컨 (Java) (0) | 2021.08.23 |
[백준] 9019. DSLR (Java) (0) | 2021.08.16 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 벨만포드
- Validation
- web
- 시뮬레이션
- BigInteger
- 브루트포스
- 다익스트라
- regex
- 정규식
- 백트래킹
- java
- 백준
- 알고리즘
- CustomHook
- matches
- dfs
- form
- BFS
- 프로그래머스
- swea
- 해시
- 이분탐색
- 그래프
- dp
- vue.js
- REACT
- 문자열
- 우선순위큐
- 구현
- 삼성역테기출
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함