Created
February 16, 2020 02:09
-
-
Save wushbin/c98d8c60351b4b85d99692e1a18537aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean validTicTacToe(String[] board) { | |
int[] row = new int[3]; | |
int[] col = new int[3]; | |
int diag = 0; | |
int anti = 0; | |
int xMove = 0; | |
int oMove = 0; | |
for (int i = 0; i < 3; i++) { | |
for (int j = 0; j < 3; j++) { | |
if (board[i].charAt(j) == 'X') { | |
row[i] += 1; | |
col[j] += 1; | |
if (i == j) diag += 1; | |
if (j + i == 2) anti += 1; | |
xMove += 1; | |
} else if (board[i].charAt(j) == 'O') { | |
row[i] -= 1; | |
col[j] -= 1; | |
if (i == j) diag -= 1; | |
if (i + j == 2) anti -= 1; | |
oMove += 1; | |
} | |
} | |
} | |
if (xMove - oMove > 1 || xMove - oMove < 0) { | |
return false; | |
} | |
boolean xWin = false; | |
for (int i = 0; i < 3; i++) { | |
xWin |= (row[i] == 3); | |
xWin |= (col[i] == 3); | |
} | |
xWin |= (diag == 3); | |
xWin |= (anti == 3); | |
boolean oWin = false; | |
for (int i = 0; i < 3; i++) { | |
oWin |= (row[i] == -3); | |
oWin |= (col[i] == -3); | |
} | |
oWin |= (diag == -3); | |
oWin |= (anti == -3); | |
if (xWin && oWin || (xMove - oMove == 0 && xWin) || (xMove - oMove == 1 && oWin)) { | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment