[LC] 348. Design Tic-Tac-Toe

Design a Tic-tac-toe game that is played between two players on a nn grid.

You may assume the following rules:

  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
class TicTacToe {

    /** Initialize your data structure here. */
    
    int[] rows;
    int[] cols;
    int diagnal;
    int antidiagnal;
    int size;
    public TicTacToe(int n) {
        this.rows = new int[n];
        this.cols = new int[n];
        this.size = 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) {
            diagnal += toAdd;
        }
        if (row + col + 1 == size) {
            antidiagnal += toAdd;
        }
        // need to use Math.abs to consider player2 
        if (Math.abs(rows[row]) == size || Math.abs(cols[col]) == size || Math.abs(diagnal) == size || Math.abs(antidiagnal) == size) {
            return player;
        }
        return 0;
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */

 

posted @ 2020-02-01 12:21  xuan_abc  阅读(139)  评论(0编辑  收藏  举报