Java O(1) short and clean


  • 0
    O
    public class TicTacToe {
    
    		int size;
    		int[] rows;
    		int[] cols;
    		int diag;
    		int cdiag;
    
    		/** Initialize your data structure here. */
    		public TicTacToe(int n) {
    			rows = new int[n];
    			cols = new int[n];
    			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 value = player == 1 ? -1 : 1;
    			int threshold = player == 1 ? -size : size;
    
    			rows[row] += value;
    			cols[col] += value;
    			if (row == col)
    				diag += value;
    			if (row + col == size - 1)
    				cdiag += value;
    
    			if (rows[row] == threshold || cols[col] == threshold
    					|| diag == threshold || cdiag == threshold)
    				return player;
    
    			return 0;
    		}
    	}

  • 0

    Could say threshold = value * size;.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.