LeetCode 794. Valid Tic-Tac-Toe State

Problem Statement


impl Solution {
pub fn valid_tic_tac_toe(board: Vec<String>) -> bool {
let (mut turns, mut x_win, mut o_win, mut diag, mut antidiag)
= (0, false, false, 0, 0);
let (mut rows, mut cols) = (vec![0; 3], vec![0; 3]);

for i in 0..3 {
for j in 0..3 {
let c = board[i].chars().nth(j).unwrap();

if c == 'X' {
turns += 1; rows[i] += 1; cols[j] += 1;
if i == j {
diag += 1;
}
if i + j == 2 {
antidiag += 1;
}
} else if c == 'O' {
turns -= 1; rows[i] -= 1; cols[j] -= 1;
if i == j {
diag -= 1;
}
if i + j == 2 {
antidiag -= 1;
}
}
}
}

x_win = (rows[0] == 3 || rows[1] == 3 || rows[2] == 3 ||
cols[0] == 3 || cols[1] == 3 || cols[2] == 3 ||
diag == 3 || antidiag == 3);
o_win = (rows[0] == -3 || rows[1] == -3 || rows[2] == -3 ||
cols[0] == -3 || cols[1] == -3 || cols[2] == -3 ||
diag == -3 || antidiag == -3);

if x_win && turns == 0 || o_win && turns == 1 {
return false;
}

return (turns == 0 || turns == 1) && (!x_win || !o_win);
}
}