348 Design tic tac toe

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

class TicTacToe {
    // rows[i]表示第i行player占据格子的贡献,player1贡献为正,player2为负
    // 只有绝对值为n才表示只有一个player有贡献(这个player全占)
    int[] rows;
    int[] cols;
    int diagonal;
    int antiDiagonal;
    int size;
    public TicTacToe(int n) {
        size = n;
        rows = new int[n];
        cols = new int[n];
    }
    
    public int move(int row, int col, int player) {
        int playerContribute = player == 1 ? 1 : -1;
        rows[row] += playerContribute;
        cols[col] += playerContribute;
        if (row == col) {
            diagonal += playerContribute;
        }
        if (row == size - col - 1) {
            antiDiagonal += playerContribute;
        }
        if (Math.abs(rows[row]) == size ||
           Math.abs(cols[col]) == size ||
           Math.abs(diagonal) == size ||
           Math.abs(antiDiagonal) == 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);
 */

这个用来判断某一行,列,对角线是否完全被某个player占据的思路其实蛮有意思的,就是单纯的计贡献数

同时注意反对角线是怎么说的。。。

Last updated