# 794. Valid Tic-Tac-Toe State

## LWC 74: 794. Valid Tic-Tac-Toe State

Problem:

A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array, and consists of characters ” “, “X”, and “O”. The ” ” character represents an empty square. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares (” “). The first player always places “X” characters, while the second player always places “O” characters. “X” and “O” characters are always placed into empty squares, never filled ones. The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over.

Example 1:

Input: board = [“O “, ” “, ” “] Output: false Explanation: The first player always plays “X”.

Example 2:

Input: board = [“XOX”, ” X “, ” “] Output: false Explanation: Players take turns making moves.

Example 3:

Input: board = [“XXX”, ” “, “OOO”] Output: false

Example 4:

Input: board = [“XOX”, “O O”, “XOX”] Output: true

Note:

• board is a length-3 array of strings, where each string board[i] has length 3.
• Each board[i][j] is a character in the set {” “, “X”, “O”}.

Java版本：

```    public boolean validTicTacToe(String[] board) {
int x_count = 0;
int o_count = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i].charAt(j) == 'X') x_count++;
else if (board[i].charAt(j) == 'O') o_count++;
}
}
char[][] map = new char[3][3];
for (int i = 0; i < 3; ++i) {
map[i] = board[i].toCharArray();
}
if (o_count > x_count || x_count - o_count > 1) return false;

if (check_win_positions(map, 'O')) {
if (check_win_positions(map, 'X')) {
return false;
}
return o_count == x_count;
}

if (check_win_positions(map, 'X') && x_count != o_count + 1) return false;

return true;
}

boolean check_win_positions(char[][] map, char player) {
for (int i = 0; i < 3; ++i) {
if (map[i][0] == map[i][1] && map[i][1] == map[i][2]
&& map[i][2] == player) {
return true;
}
}

for (int j = 0; j < 3; ++j) {
if (map[0][j] == map[1][j] && map[1][j] == map[2][j]
&& map[2][j] == player) {
return true;
}
}

if (map[0][0] == map[1][1] && map[1][1] == map[2][2] && map[2][2]  == player ||
map[0][2] == map[1][1] && map[1][1] == map[2][0] && map[2][0] == player)
return true;

return false;
}```

Python版本：

```class Solution(object):
def check_win_positions(self, board, player):
#Check the rows
for i in range(len(board)):
if board[i][0] == board[i][1] == board[i][2] == player:
return True

#Check the columns
for i in range(len(board)):
if board[0][i] == board[1][i] == board[2][i] == player:
return True

#Check the diagonals
if board[0][0] == board[1][1] == board[2][2]  == player or \
board[0][2] == board[1][1] == board[2][0] == player:
return True

return False

def validTicTacToe(self, board):
"""
:type board: List[str]
:rtype: bool
"""

x_count, o_count = 0, 0
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == "X":
x_count += 1
elif  board[i][j] == "O":
o_count += 1

if o_count > x_count or x_count-o_count>1:
return False

if self.check_win_positions(board, 'O'):
if self.check_win_positions(board, 'X'):
return False
return o_count == x_count

if self.check_win_positions(board, 'X') and x_count!=o_count+1:
return False

return True```

0 条评论

• ### LWC 55：714. Best Time to Buy and Sell Stock with Transaction Fee

LWC 55：714. Best Time to Buy and Sell Stock with Transaction Fee 传送门：714. Best T...

• ### 算法细节系列（23）：回溯

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• ### 算法细节系列（13）：买卖股票

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• ### Android实现状态栏和虚拟按键背景颜色的变化实例代码详解

今天介绍一下，我在项目开发过程中，实现状态栏和虚拟按键背景颜色变化的方法，实现方式是，通过隐藏系统的状态栏和虚拟按键的背景，实现图片和背景显示到状态栏和虚拟按键...

• ### 剑指offer【10~19】

f(n) = f(n-1) + f(n-2) + ... + f(0)，其中 f(i) 表示从第 i 层跳到第 n 层的跳法。化简的 f(n) = 2 * f(...

• ### 编码篇-iOS开发中的奇巧小伎

最近搜集了自己以前的笔记中的一些小知识点，归为这篇文章，都是亲测有效的奇巧小伎，当你使用到时，你会大呼过瘾的。

• ### 【C语言简单说】十三：逻辑运算符||

这一节我们来说说逻辑或||，其实很简单的，既然你们理解了第一个逻辑与，那么逻辑或就没什么难度了。

• ### 【下载】TensorFlow机器学习教程手把手书谱

【导读】 来自 Nick McClure 的电子书《TensorFlow Machine Learning Cookbook》这本书主要是基于TensorFlo...

• ### 超全 | 只有高手才知道的C语言高效编程与代码优化方法（二）

在if(a>10 && b=4)这样的语句中，确保AND表达式的第一部分最可能较快的给出结果（或者最早、最快计算），这样第二部分便有可能不需要执行。