forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Valid Tic-Tac-Toe State.java
79 lines (75 loc) · 2.21 KB
/
Valid Tic-Tac-Toe State.java
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
71
72
73
74
75
76
77
78
79
class Solution {
public boolean validTicTacToe(String[] board) {
//cnt number of X and O
int x = cntNumber('X', board);
//this check can be omitted, it can be covered in the second number check.
if(x >5){
return false;
}
int o = cntNumber('O', board);
if(x < o || x > o + 1){
return false;
}
//if(x <3 ) true, no need to see winning
if(o >= 3){
//if x has won, but game doesnt stop
if(x == o && hasWon('X', board)){
return false;
}
//if o has won, but game doesnt stop
if( x > o && hasWon('O', board) ){
return false;
}
}
return true;
}
private int cntNumber(char target, String[] board){
int res = 0;
for(int i = 0; i<3; i++) {
for(int j = 0; j<3; j++) {
if(target == board[i].charAt(j)){
res++;
}
}
}
return res;
}
private boolean hasWon(char target, String[] board){
String toWin = Character.toString(target).repeat(3);
for(int i = 0; i<3; i++) {
if(board[i].equals(toWin)){
return true;
}
}
for(int j = 0; j<3; j++) {
boolean col = true;
for(int i = 0; i<3; i++) {
col = col && target == board[i].charAt(j);
if(!col){
break;
}
}
if(col){
return true;
}
}
//check diagonal. If center is not target, not possible to form diag win.
if(target != board[1].charAt(1)){
return false;
}
boolean diagonal1 = target == board[0].charAt(0);
//only proceed if the first letter match. Otherwise might get false positive
if(diagonal1){
if(target == board[2].charAt(2)){
return true;
}
}
boolean diagonal2 = target == board[0].charAt(2);
if(diagonal2){
if(target == board[2].charAt(0)){
return true;
}
}
return false;
}
}