current position：Home>leetcode 1275. Find Winner on a Tic Tac Toe Game（python）
leetcode 1275. Find Winner on a Tic Tac Toe Game（python）
2022-01-31 11:19:19 【Wang Daya】
「 This is my participation 11 The fourth of the yuegengwen challenge 12 God , Check out the activity details ：2021 One last more challenge 」
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
- Players take turns placing characters into empty squares ' '.
- The first player A always places 'X' characters, while the second player B always places 'O' characters.
- 'X' and 'O' characters are always placed into empty squares, never on filled ones.
- The game ends when there are three 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.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]] Output: "A" Explanation: A wins, they always play first. Copy code
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]] Output: "B" Explanation: B wins. Copy code
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. Copy code
Input: moves = [[0,0],[1,1]] Output: "Pending" Explanation: The game has not finished yet. Copy code
1 <= moves.length <= 9 moves[i].length == 2 0 <= rowi, coli <= 2 There are no repeated elements on moves. moves follow the rules of tic tac toe. Copy code
According to the meaning , Two players in one 3*3 Play in the square called Tic-tac-toe The game of , The following rules ：
- Players take turns putting characters into empty squares .
- The first player A Always place 'X' character , And the second player B Always place 'O' character .
- 'X' and 'O' Characters are always placed in empty squares
- When three are the same （ Non empty ） Fill any line with characters 、 Column or diagonal line , Game over .
- If all squares are not empty , The game will end .
- If the game is over , You can't do anything anymore .
Given a two-dimensional array of integers moves , among move[i] = [rowi,coli] It means the first one i One operation is in grid[rowi][coli] on . If A or B Can meet three consecutive characters in the same line 、 Same column or diagonal , Then return to the winner of the game . If the game ends in a draw , Then return to Draw . If there is still room to continue the game , Please return Pending .
In fact, the topic is also very simple after understanding , Ideas as follows ：
- take A Take out all the positions in the box and put them into the list A in , take B Take out all the positions in the box and put them into the list B in
- Because there are only eight conditions to win , So list them all and put them in winCom in
- Traverse winCom Every win in com , If the judgment list A and com If the elements in the are equal, it returns A , Similarly, if the judgment list B and com If the elements in the are equal, it returns B
- Otherwise, if the list A And list B The sum of the length of is 9 It means a draw , Go straight back to Draw
- Otherwise go straight back to Pending
class Solution(object): def tictactoe(self, moves): """ :type moves: List[List[int]] :rtype: str """ winCom = [[[0,0],[0,1],[0,2]] , [[1,0],[1,1],[1,2]], [[2,0],[2,1],[2,2]], [[0,0],[1,0],[2,0]],[[0,1],[1,1],[2,1]],[[0,2],[1,2],[2,2]], [[0,0],[1,1],[2,2]],[[0,2],[1,1],[2,0]]] A = [c for c in moves[0:len(moves):2]] B = [c for c in moves[1:len(moves):2]] for com in winCom: if self.isWin(A, com): return 'A' if self.isWin(B, com): return 'B' if len(A)+len(B)==9: return "Draw" return "Pending" def isWin(self, L, com): result = 0 for c in L: if c in com: result += 1 return result == 3 Copy code
Runtime: 24 ms, faster than 52.05% of Python online submissions for Find Winner on a Tic Tac Toe Game. Memory Usage: 13.3 MB, less than 71.11% of Python online submissions for Find Winner on a Tic Tac Toe Game. Copy code
Original link ：leetcode.com/problems/fi…
Your support is my greatest motivation
author[Wang Daya],Please bring the original link to reprint, thank you.
The sidebar is recommended
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes ｜ 538 ｜ 1038 (Java / C / C + + / Python / go / trust)
guess what you like
How IOS developers learn python programming 3-operator 2
How IOS developers learn python programming 2-operator 1
[Python applet] 8 lines of code to realize file de duplication
Python uses the pynvml tool to obtain the working status of GPU
Data mining: Python actual combat multi factor analysis
Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
Use Python VTK to batch read 2D slices and display 3D models
Complete image cutting using Python version VTK
Python interface automation test framework (basic) -- common data types Dict
Django (make an epidemic data report)
- Python specific text extraction in actual combat challenges the first step of efficient office
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert（python）
- leetcode 2062. Count Vowel Substrings of a String（python）
- Analysis of Matplotlib module of Python visualization
- Django permission management
- Python integrated programming -- visual hot search list and new epidemic situation map
- [Python data collection] scripy realizes picture download
- Python interface automation test framework (basic part) -- loop statement of process control for & while
- Daily python, Chapter 9, while loop
- Van * Python | save the crawled data with docx and PDF
- Five life saving Python tips
- Django frequency control
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence（python）
- leetcode 2027. Minimum Moves to Convert String（python）
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph（python）
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores（python）
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching