348. Design Tic-Tac-Toe

Design a Tic-tac-toe game that is played between two players on a n x n grid.

You may assume the following rules:

A move is guaranteed to be valid and is placed on an empty block.
Once a winning condition is reached, no more moves is allowed.
A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Follow up:
Could you do better than O(n2) per move() operation?

思路: 先给出最naive的解法,每下一步去查下所有的行,列,对角线跟斜对角线是否满足。 这样的话时间复杂度为O(n^2).

public class TicTacToe {
    private int[][] board;
    private int n;

    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        this.board = new int[n][n];
        this.n = 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) {
        board[row][col] = player;
        if(isWin(board, row, col)) {
            return player;
        }
        return 0;
    }

    public boolean isWin(int[][] board,int row, int col) {
        boolean isRow = true, isCol = true, isDig = true, isAntiDig = true;
        // check row
        for (int i = 0; i < n - 1; i++) {
            if (board[row][i] != board[row][i + 1] )
                isRow = false;
        }
        // check col
        for (int j = 0; j < n - 1; j++) {
            if (board[j][col] != board[j + 1][col])
                isCol = false;
        }
        // check diagional
        if (row == col) {
            for (int i = 0; i < n - 1; i++) {
                if (board[i][i] != board[i + 1][i + 1]) 
                    isDig = false;
            }
        } else {
            isDig = false;
        }
        if (row + col == n - 1) {
            // check anti diagional
            for (int i = 0; i < n - 1; i++) {
                if (board[i][n - 1 - i] != board[i + 1][n - 2 - i]) 
                    isAntiDig = false;
            } 
        } else {
            isAntiDig = false;
        }
        return isRow || isCol || isDig || isAntiDig;
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */

在followup中,问是否能把时间复杂度降到O(n^2)以下,我们只保存列,行,更对角线元素的状态。 play 1对应的值为1, play2对应的值为-1;

public class TicTacToe {
    private int[] columns; 
    private int[] rows;
    private int diagonal;
    private int antiDiagonal;
    private int n;

    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        columns = new int[n];
        rows = new int[n];
        diagonal = 0;
        antiDiagonal = 0;
        this.n = 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) {
        //Take player 1 and 2 as value of 1 and -1;
        int number = player == 1 ? 1 : -1;  // place the player, identify which player; player 1 as 1, player 2 as -1;
        rows[row] += number;   // save the value to row, col, diag, antiDiag
        columns[col] += number;
        if (row == col) {
            diagonal += number;
        }
        if (row == n - 1 - col) {
            antiDiagonal += number;
        }
        if (Math.abs(rows[row]) == n || Math.abs(columns[col]) == n ||  // winning condition
             Math.abs(diagonal) == n || Math.abs(antiDiagonal) == n)
            return player;
        return 0;    
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s