Posted onInLeetcodeViews: Words count: 2kReading time ≈2 mins.
348.Design Tic-Tac-Toe
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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 n of 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 board n. - int move(int row, int col, int player) Indicates that the player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return - 0 if there is no winner after the move, - 1 if player 1 is the winner after the move, or - 2 if player 2 is the winner after the move.
Difficulty : Medium
Solution
This is a problem where we can use the concept of rows, columns, and diagonals to keep track of the current player’s marks. In an nxn TicTacToe board, a player wins if they have n marks on any row, column or diagonal.
We can create four integer arrays: rows, columns, and two diagonals. Player1 will +1 to the position, and player2 will -1. When any position reaches n or -n, that means player1 or player2 wins.
public class TicTacToe { private int[] rows; private int[] cols; private int diagonal; private int antiDiagonal;
/** Initialize your data structure here. */ public TicTacToe(int n) { rows = new int[n]; cols = new int[n]; } /** * Player {player} makes a move at ({row}, {col}). * * @param row The row of the board. * @param col The column of the board. * @param player The player, can be either 1 or 2. * @return The current winning condition, can be either: * 0: No one wins. * 1: Player 1 wins. * 2: Player 2 wins. */ public int move(int row, int col, int player) { int toAdd = player == 1 ? 1 : -1;