LC: 348. Design Tic Tac Toe
https://leetcode.com/problems/design-tic-tac-toe/
348. Design Tic-Tac-Toe
Assume the following rules are for the tic-tac-toe game on an n x n board between two players:
A move is guaranteed to be valid and is placed on an empty block.
Once a winning condition is reached, no more moves are allowed.
A player who succeeds in placing
nof their marks in a horizontal, vertical, or diagonal row wins the game.
Implement the TicTacToe class:
TicTacToe(int n)Initializes the object the size of the boardn.int move(int row, int col, int player)Indicates that the player with idplayerplays at the cell(row, col)of the board. The move is guaranteed to be a valid move.
Example 1:
Input
["TicTacToe", "move", "move", "move", "move", "move", "move", "move"]
[[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]]
Output
[null, 0, 0, 0, 0, 0, 0, 1]
Explanation
TicTacToe ticTacToe = new TicTacToe(3);
Assume that player 1 is "X" and player 2 is "O" in the board.
ticTacToe.move(0, 0, 1); // return 0 (no one wins)
|X| | |
| | | | // Player 1 makes a move at (0, 0).
| | | |
ticTacToe.move(0, 2, 2); // return 0 (no one wins)
|X| |O|
| | | | // Player 2 makes a move at (0, 2).
| | | |
ticTacToe.move(2, 2, 1); // return 0 (no one wins)
|X| |O|
| | | | // Player 1 makes a move at (2, 2).
| | |X|
ticTacToe.move(1, 1, 2); // return 0 (no one wins)
|X| |O|
| |O| | // Player 2 makes a move at (1, 1).
| | |X|
ticTacToe.move(2, 0, 1); // return 0 (no one wins)
|X| |O|
| |O| | // Player 1 makes a move at (2, 0).
|X| |X|
ticTacToe.move(1, 0, 2); // return 0 (no one wins)
|X| |O|
|O|O| | // Player 2 makes a move at (1, 0).
|X| |X|
ticTacToe.move(2, 1, 1); // return 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|Constraints:
2 <= n <= 100player is
1or2.0 <= row, col < n(row, col)are unique for each different call tomove.At most
n2calls will be made tomove.
Follow-up: Could you do better than O(n2) per move() operation?
The Essence: Anstatt jedes Mal zu prüfen, ob eine Gewinnbedingung erfüllt ist, kann man die Anzahl der Züge jedes Spielers auf der Diagonale, Anti-Diagonale, jeder Spalte und jeder Reihe speichern. Wenn von einem Spieler einen neuen Zug gemacht wird, sollte das Programm in der Lage sein zu überprüfen, ob eine der Bedingungen für einen Gewinn erfüllt ist. Die Tatsache, der hier zu beachten ist, ist, dass die Verwendung gespeicherter Daten tatsächlich effizienter sein kann, als jedes Mal neu zu berechnen.
Details:
Für die Speicherung kann man einfach Arrays nutzen. Bei jedem Zug soll man diese Arrays kontrollieren. Solution(s) and Further Explanation:
Default Code:
Last updated