348.Design Tic-Tac-Toe

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;

rows[row] += toAdd;
cols[col] += toAdd;
if (row == col)
{
diagonal += toAdd;
}

if (col == (cols.length - row - 1))
{
antiDiagonal += toAdd;
}

int size = rows.length;
if (Math.abs(rows[row]) == size ||
Math.abs(cols[col]) == size ||
Math.abs(diagonal) == size ||
Math.abs(antiDiagonal) == size)
{
return player;
}

return 0;
}
}