Advertisement
Guest User

348. Design Tic-Tac-Toe

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