LeetCode 794. 【Java】794. Valid Tic-Tac-Toe State
原题链接
中等
作者:
tt2767
,
2020-03-30 23:41:54
,
所有人可见
,
阅读 519
/**
1. 判断井字棋是否合法, 那么把每个条件都细化为逻辑来判断
2. 可以根据 X赢 或 O赢分为4中情况讨论
2.1 X赢了, O没赢: x先手, 所以此时合法情况是 x 比 o 多一个
2.1 X没赢, O赢了: x先手, 所以此时合法情况是 x 与 o 相等
2.1 X没赢, O没赢: 中间情况 0 <= count(x) - count(o) <= 1
2.1 X赢了, O赢了: 必定非法
3. 怎么判断有没有人赢: 当有 3 个相同(且非空)的字符填充任何行、列或对角线时,游戏结束。
*/
class Solution {
final static int n = 3;
public boolean validTicTacToe(String[] board) {
int cx = 0 , co = 0;
char[][] plant = new char[n][n];
for (int i = 0 ; i < n; i ++) plant[i] = board[i].toCharArray();
for (int i = 0 ; i < n ;i ++){
for(int j = 0; j < n ; j++ ){
if (plant[i][j] == 'X') cx ++;
else if (plant[i][j] == 'O') co ++;
}
}
int diff = cx - co;
boolean xIsWiner = isWiner('X', plant);
boolean oIsWiner = isWiner('O', plant);
if (xIsWiner && !oIsWiner) return diff == 1;
if (oIsWiner && !xIsWiner) return diff == 0;
if (!xIsWiner && !oIsWiner) return 0 <= diff && diff <= 1;
return false;
}
public boolean isWiner(char player, char[][] plant){
int[] row = new int[n];
int[] col = new int[n];
int ldig = 0, rdig = 0;
for (int i = 0 ; i < n; i++){
for (int j = 0; j < n ; j++){
if (plant[i][j] != player) continue;
row[i]++;
col[j]++;
if (i == j) ldig ++;
if (i + j == n-1) rdig ++;
if (row[i] == 3 || col[j] == 3 || ldig == 3 || rdig == 3) return true;
}
}
return false;
}
}