- 794.有效的井字游戏
- 题目描述
- 思路
- 分类讨论
- Python实现
- Java实现
794.有效的井字游戏 题目描述
有效的井字游戏
思路 分类讨论
根据游戏板生效的规则:
- 玩家需要轮流将字符放入空位中。第一个玩家放"X",第二个玩家放"O"。因为第一个玩家是先手,所以场上的"X"的个数一定大于等于"O"的个数。
- "X"和"O"只允许放在空位,不允许对已放有字符的位置进行填充,则限制了一行只能出现三个字符。
- 当有3个相同且非空的字符填充了任意行、列或对角线,则游戏结束。当所有位置非空,则游戏结束。游戏结束后,不允许再放入字符。因此不可能出现两个玩家都获胜的情况。
- 获胜玩家一定是在放自己的棋后就结束比赛。
- 如果是第一个玩家获胜,则场上"X"的个数比"O"的个数多1。
- 如果是第二个玩家获胜,则场上"X"的个数与"O"的个数相等。
class Solution: def win(self, board, p): return any(board[i][0] == p and board[i][1] == p and board[i][2] == p or board[0][i] == p and board[1][i] == p and board[2][i] == p for i in range(3)) or (board[0][0] == p and board[1][1] == p and board[2][2] == p or board[0][2] == p and board[1][1] == p and board[2][0] == p) def validTicTacToe(self, board: List[str]) -> bool: o_count = sum(row.count('O') for row in board) x_count = sum(row.count('X') for row in board) return not (o_count != x_count and o_count != x_count - 1 or o_count != x_count and self.win(board, 'O') or o_count != x_count - 1 and self.win(board, 'X'))Java实现
class Solution { public boolean validTicTacToe(String[] board) { int xCount = 0, oCount = 0; for (String row : board) { for (char c : row.toCharArray()) { xCount = (c == 'X') ? (xCount + 1) : xCount; oCount = (c == 'O') ? (oCount + 1) : oCount; } } if (oCount != xCount && oCount != xCount - 1) { return false; } if (win(board, 'X') && oCount != xCount - 1) { return false; } if (win(board, 'O') && oCount != xCount) { return false; } return true; } public boolean win(String[] board, char p) { for (int i = 0; i < 3; ++i) { if (p == board[0].charAt(i) && p == board[1].charAt(i) && p == board[2].charAt(i)) { return true; } if (p == board[i].charAt(0) && p == board[i].charAt(1) && p == board[i].charAt(2)) { return true; } } if (p == board[0].charAt(0) && p == board[1].charAt(1) && p == board[2].charAt(2)) { return true; } if (p == board[0].charAt(2) && p == board[1].charAt(1) && p == board[2].charAt(0)) { return true; } return false; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)