Share my straightforward OO solution


  • 0
    H
    import java.util.NoSuchElementException;
    public class TicTacToe {
        
        private Player p1;
        private Player p2;
    
        public TicTacToe(int n) {
            p1 = new Player(n);
            p2 = new Player(n);
        }
    
        public int move(int row, int col, int player) {
            if (player == 1) {
                p1.move(row, col);
            } else if (player == 2) {
                p2.move(row, col);
                
            } else {
                throw new NoSuchElementException();
            }
            return winner();
        }
        
        private int winner() {
            if (p1.canWin()) {
                return 1;
            } else if (p2.canWin()) {
                return 2;
            }
            return 0;
        }
    }
    
    class Player {
        
        private boolean[][] board;
        private int[] rows;
        private int[] cols;
        
        public Player(int n) {
            board = new boolean[n][n];
            rows = new int[n];
            cols = new int[n];
            Arrays.fill(rows, n * (n + 1) / 2);
            Arrays.fill(cols, n * (n + 1) / 2);
        }
        
        public void move(int row, int col) {
            board[row][col] = true;
            rows[row] -= col + 1;
            cols[col] -= row + 1;
        }
        
        public boolean canWin() {
            for (int i = 0; i < rows.length; i++) {
                if (rows[i] == 0 || cols[i] == 0) {
                    return true;
                }
            }
            boolean d1 = true;
            boolean d2 = true;
            for (int i = 0; i < board.length; i++) {
                d1 = d1 && board[i][i];
                d2 = d2 && board[board.length - 1 - i][i];
            }
            return d1 || d2;
        }
    }
    

Log in to reply
 

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