Created
December 28, 2025 20:49
-
-
Save Allan-Gong/1bc75d86cc27e1e2d2e1ce4ac38e91bf to your computer and use it in GitHub Desktop.
DesignTicTacToe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test; | |
| // The key observation is that in order to win Tic-Tac-Toe you must have the entire row or column. | |
| public class DesignTicTacToe { | |
| class TicTacToe { | |
| int[] rows; | |
| int[] cols; | |
| int d1 = 0; // 正对角线 | |
| int d2 = 0; // 反对角线 | |
| int n; | |
| /** Initialize your data structure here. */ | |
| public TicTacToe(int n) { | |
| this.n = 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 p = player == 1 ? 1 : -1; // 关键一步 | |
| rows[row] += p; | |
| cols[col] += p; | |
| if (row == col) d1 += p; // 正对角线 | |
| if (row+col+1 == n) d2 += p; // 反对角线 | |
| if (Math.abs(rows[row]) == n || Math.abs(cols[col]) == n || Math.abs(d1) == n || Math.abs(d2) == n) { | |
| return player; | |
| } | |
| return 0; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment