tic tac toe php,[Leetcode] Design Tic-Tac-Toe 设计精子游戏

本文介绍了一种实现Tic-Tac-Toe游戏的方法,使用了大小为n的一维数组来跟踪每行和每列的状态,同时记录对角线和逆对角线的情况。通过这种方式,可以在O(1)时间内检查是否有玩家获胜。

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.

复杂度

O(1) 时间 O(N) 空间

思路

数据结构:

两个大小为n的一维数组计数器rows和cols,对角线计数器diag和逆对角线计数器anti_diag

思路:

如果玩家1在第一行某一列放了一个子,那么rows[row]自增1,cols[col]自增1,如果玩家2在第一行某一列放了一个子,则rows[row]自减1,cols[col]自减1,于是当rows[row]等于n或者-n的时候,或者cols[col]等于n或者-n,则游戏结束返回该玩家即可,对角线和逆对角线如法炮制

注意

注意判断对角线的时候,是两个if并列的,不是if else,因为一个点有可能既是正对角线,也是反对角线,那就是中间的点。

代码

public class TicTacToe {

int n;

int[] rows;

int[] cols;

int diagonal;

int anti_diagonal;

int wins;

/** Initialize your data structure here. */

public TicTacToe(int n) {

this.n = n;

rows = new int[n];

cols = new int[n];

diagonal = 0;

anti_diagonal = 0;

wins = 0;

}

/** 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) {

if (player == 1) {

rows[row]++;

cols[col]++;

if (row == col)

diagonal++;

if (row + col == n - 1)

anti_diagonal++;

}

else if (player == 2) {

rows[row]--;

cols[col]--;

if (row == col)

diagonal--;

if (row + col == n - 1)

anti_diagonal--;

}

if (rows[row] == n || cols[col] == n || diagonal == n || anti_diagonal == n)

wins = 1;

else if (rows[row] == -n || cols[col] == -n || diagonal == -n || anti_diagonal == -n)

wins = 2;

return wins;

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值