Advertisement
1988coder

348. Design Tic-Tac-Toe

Jan 19th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/design-tic-tac-toe/
  2. /**
  3.  * Time Complexity: Initialization -> O(1). Move -> O(1).
  4.  *
  5.  * Space Complexity: O(N). This is required to store scores at each row and each
  6.  * column.
  7.  */
  8. class TicTacToe {
  9.  
  10.     int[] rows;
  11.     int[] cols;
  12.     int diag1;
  13.     int diag2;
  14.     int size;
  15.  
  16.     /** Initialize your data structure here. */
  17.     public TicTacToe(int n) {
  18.         size = n;
  19.         rows = new int[n];
  20.         cols = new int[n];
  21.         diag1 = 0;
  22.         diag2 = 0;
  23.     }
  24.  
  25.     /**
  26.      * Player {player} makes a move at ({row}, {col}).
  27.      *
  28.      * @param row    The row of the board.
  29.      * @param col    The column of the board.
  30.      * @param player The player, can be either 1 or 2.
  31.      * @return The current winning condition, can be either: 0: No one wins. 1:
  32.      *         Player 1 wins. 2: Player 2 wins.
  33.      */
  34.     public int move(int row, int col, int player) {
  35.         int inc = player == 1 ? 1 : -1;
  36.  
  37.         rows[row] += inc;
  38.         cols[col] += inc;
  39.         if (row == col) {
  40.             diag1 += inc;
  41.         }
  42.         if (row + col == size - 1) {
  43.             diag2 += inc;
  44.         }
  45.  
  46.         if (Math.abs(rows[row]) == size || Math.abs(cols[col]) == size || Math.abs(diag1) == size
  47.                 || Math.abs(diag2) == size) {
  48.             return player;
  49.         }
  50.  
  51.         return 0;
  52.     }
  53. }
  54.  
  55. /**
  56.  * Your TicTacToe object will be instantiated and called as such: TicTacToe obj
  57.  * = new TicTacToe(n); int param_1 = obj.move(row,col,player);
  58.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement