首页 > 其他 > 详细

[LC] 348. Design Tic-Tac-Toe

时间:2020-02-01 13:17:10      阅读:69      评论:0      收藏:0      [点我收藏+]

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

You may assume the following rules:

  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
class TicTacToe {

    /** Initialize your data structure here. */
    
    int[] rows;
    int[] cols;
    int diagnal;
    int antidiagnal;
    int size;
    public TicTacToe(int n) {
        this.rows = new int[n];
        this.cols = new int[n];
        this.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 toAdd = player == 1 ? 1 : -1;
        rows[row] += toAdd;
        cols[col] += toAdd;
        if (row == col) {
            diagnal += toAdd;
        }
        if (row + col + 1 == size) {
            antidiagnal += toAdd;
        }
        // need to use Math.abs to consider player2 
        if (Math.abs(rows[row]) == size || Math.abs(cols[col]) == size || Math.abs(diagnal) == size || Math.abs(antidiagnal) == size) {
            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);
 */

 

[LC] 348. Design Tic-Tac-Toe

原文:https://www.cnblogs.com/xuanlu/p/12248093.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!