[LeetCode]#1275 Find Winner on a Tic Tac Toe Game

Fatboy Slim
3 min readMar 12, 2020

--

Environment: Python 3.7

Key technique: slice, function all

Example 1:

Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"

Example 2:

Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "

Example 3:

Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"

Example 4:

Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X "
" O "
" "

Analysis: This problem need to consider four situation which are A win, B win, pending, and Draw. We can judge 1. A win or B win, 2. Draw, and 3. Pending. Set win condition as [0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]

Solution:

class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
array = []
l=len(moves)
l2=len(wins)
for i in moves:
array.append(3*i[0] + i[1])
A = array[0:l:2]
B = array[1:l:2]
B.sort()
A.sort()
for wins in wins:
if all([i in A for i in wins]):
return 'A'
elif all([i in B for i in wins]):
return 'B'
if l ==9:
return "Draw"
else:
return "Pending"

Submitted result:

Lesson learn:

wins=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]; A=[1,3,4,5] . Never see below code method and analyze as below.

for wins in wins:
if all([i in A for i in wins]):
return 'A'

for wins in wins: print(wins)

output:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[0, 3, 6]
[1, 4, 7]
[2, 5, 8]
[0, 4, 8]
[2, 4, 6]

for i in wins: print(i)

output:
2
4
6

Namely we can observe below debug output which are 1,3,4 and will check A has this value or not.

Change code and can get value True.

Reference:

https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/519287/Python-20ms-Solution

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet