congr / world

2 stars 1 forks source link

LeetCode : 348. Design Tic-Tac-Toe #465

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/design-tic-tac-toe/

image image

congr commented 5 years ago
class TicTacToe {
    int N;
    int[] rows, cols;
    int diag, anti;

    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        rows = new int[n];
        cols = new int[n];
        this.N = 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 v = (player == 1) ? 1 : -1; // player 1 -> mark 1, player 2 -> mark -1

        rows[row] += v;
        cols[col] += v;

        if (row == col) diag += v;
        if (N-row-1 == col) anti += v;

        if (Math.abs(rows[row]) == N || Math.abs(cols[col]) == N || 
            Math.abs(diag) == N || Math.abs(anti) == N) return player;
        else 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);
 */