1275. Find Winner on a Tic Tac Toe Game

91 阅读1分钟

image.png

image.png

image.png

方法

  • 两个玩家,其中一个玩家下棋,在格子里记1分,另一个记-1。
  • 产生赢家的条件:某一行/某一列/两个对角线之一 的分数为3或者-3

image.png

class Solution {
    public String tictactoe(int[][] moves) {
        int n = 3;
        int[] rowScore = new int[n], colScore = new int[n]; // score of each row
        int diagonol1Score = 0, diagonol2Score = 0;
        int player = 1;
        for (int[] move : moves) {
            int row = move[0], col = move[1];

            rowScore[row] += player;
            colScore[col] += player;
            
            if (row == col) {
                diagonol1Score += player;
            }
            if (row + col + 1 == n) {
                diagonol2Score += player;
            }

            // check winning conditions
            if (Math.abs(rowScore[row]) == n || Math.abs(colScore[col]) == n 
            || Math.abs(diagonol1Score) == n || Math.abs(diagonol2Score) == n) {
                return player == 1 ? "A" : "B";
            }

            player *= -1; // switch user
        }

        return moves.length == n * n ? "Draw" : "Pending";
    }
}