Design a Tic-tac-toe game that is played between two players on a n x n 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.

Example:

Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.

TicTacToe toe = new TicTacToe(3);

toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | | // Player 1 makes a move at (0, 0).
| | | | toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 2 makes a move at (0, 2).
| | | | toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 1 makes a move at (2, 2).
| | |X| toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 2 makes a move at (1, 1).
| | |X| toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 1 makes a move at (2, 0).
|X| |X| toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| | // Player 2 makes a move at (1, 0).
|X| |X| toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|

Follow up:
Could you do better than O(n2) per move()

Hint:

Could you trade extra space such that move() operation can be done in O(1)?
You need two arrays: int rows[n], int cols[n], plus two variables: diagonal, anti_diagonal.

CareerCup上的原题,请参见我之前的博客17.2 Tic Tac Toe。我们首先来O(n2)的解法,这种方法的思路很straightforward,就是建立一个nxn大小的board,其中0表示该位置没有棋子,1表示玩家1放的子,2表示玩家2。那么棋盘上每增加一个子,我们都扫描当前行列,对角线,和逆对角线,看看是否有三子相连的情况,有的话则返回对应的玩家,没有则返回0,参见代码如下:

解法一:

class TicTacToe {
public:
/** Initialize your data structure here. */
TicTacToe(int n) {
board.resize(n, vector<int>(n, ));
} int move(int row, int col, int player) {
board[row][col] = player;
int i = , j = , n = board.size();
for (j = ; j < n; ++j) {
if (board[row][j] != board[row][j - ]) break;
}
if (j == n) return player;
for (i = ; i < n; ++i) {
if (board[i][col] != board[i - ][col]) break;
}
if (i == n) return player;
if (row == col) {
for (i = ; i < n; ++i) {
if (board[i][i] != board[i - ][i - ]) break;
}
if (i == n) return player;
}
if (row + col == n - ) {
for (i = ; i < n; ++i) {
if (board[n - i - ][i] != board[n - i][i - ]) break;
}
if (i == n) return player;
}
return ;
} private:
vector<vector<int>> board;
};

Follow up中让我们用更高效的方法,那么根据提示中的,我们建立一个大小为n的一维数组rows和cols,还有变量对角线diag和逆对角线rev_diag,这种方法的思路是,如果玩家1在第一行某一列放了一个子,那么rows[0]自增1,如果玩家2在第一行某一列放了一个子,则rows[0]自减1,那么只有当rows[0]等于n或者-n的时候,表示第一行的子都是一个玩家放的,则游戏结束返回该玩家即可,其他各行各列,对角线和逆对角线都是这种思路,参见代码如下:

解法二:

class TicTacToe {
public:
/** Initialize your data structure here. */
TicTacToe(int n): rows(n), cols(n), N(n), diag(), rev_diag() {} int move(int row, int col, int player) {
int add = player == ? : -;
rows[row] += add;
cols[col] += add;
diag += (row == col ? add : );
rev_diag += (row == N - col - ? add : );
return (abs(rows[row]) == N || abs(cols[col]) == N || abs(diag) == N || abs(rev_diag) == N) ? player : ;
} private:
vector<int> rows, cols;
int diag, rev_diag, N;
};

参考资料:

https://leetcode.com/problems/design-tic-tac-toe/

https://discuss.leetcode.com/topic/44548/java-o-1-solution-easy-to-understand

https://discuss.leetcode.com/topic/44605/c-time-o-1-space-o-n-short-simple-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Design Tic-Tac-Toe 设计井字棋游戏的更多相关文章

  1. [LeetCode] 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 fol ...

  2. [Swift]LeetCode348. 设计井字棋游戏 $ 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 fol ...

  3. [CareerCup] 17.2 Tic Tac Toe 井字棋游戏

    17.2 Design an algorithm to figure out if someone has won a game oftic-tac-toe. 这道题让我们判断玩家是否能赢井字棋游戏, ...

  4. [LeetCode] 794. Valid Tic-Tac-Toe State 验证井字棋状态

    A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to r ...

  5. 井字棋游戏升级版 - TopTicTacToe项目 简介

    一.游戏简介 井字棋是一款世界闻名的游戏,不用我说,你一定知道它的游戏规则. 这款游戏简单易学,玩起来很有意思,不过已经证明出这款游戏如果两个玩家都足够聪明的话, 是很容易无法分出胜负的,即我们得到的 ...

  6. JavaFX 井字棋游戏

    利用JavaFX设计一个井字棋游戏,其中包括了能够与玩家对战的AI.AI的实现相比五子棋来说要简单得多,可以保证AI在后手情况下绝对不会输,具体实现如下: /* * To change this li ...

  7. C++井字棋游戏,DOS界面版

    据说有一个能保证不败的算法.明天看看先再写个PVC版的. 正题.今天无聊写了个井字棋游戏,顺便逐渐让自己习惯良好的代码风格,放上来给新手学习学习. jzq2.cpp /* N字棋游戏PVP版,DOS版 ...

  8. Java井字棋游戏

    试着写了一个井字棋游戏,希望各位能给予一些宝贵的建议. 一.棋盘类 package 井字棋游戏; public class ChessBoard { private int number; Perso ...

  9. [C++] 井字棋游戏源码

    TicTac.h #define EX 1 //该点左鼠标 #define OH 2 //该点右鼠标 class CMyApp : public CWinApp { public: virtual B ...

随机推荐

  1. 探究负边距(negative margin)原理

    W3C规范在介绍margin时有这样一句话: Negative values for margin properties are allowed, but there may be implement ...

  2. ASP.NET 中 OutputCache 指令参数详解

    使用@ OutputCache指令使用@ OutputCache指令,能够实现对页面输出缓存的一般性需要.@ OutputCache指令在ASP.NET页或者页中包含的用户控件的头部声明.这种方式非常 ...

  3. code

    using System;using System.Threading; namespace ThreadLocalTest{    public class MyObject    {       ...

  4. Angularjs环境搭建

    Angularjs架构搭建      1.搭建Angularjs项目           1)在package.json中配置如下,然后 npm install下载包     {   "na ...

  5. visual studio 编辑窗口 设置固定选项卡 使窗口选项卡多行显示

    工具>选项> 确定后 如图就可以多行显示了.

  6. ActiveMQ(li)

    一.ActiveMQ 首先,ActiveMQ不是一个框架,它不是struct,webx,netty这种框架,它更像是tomcat服务器,因为你使用它之前必须启动它,activeMQ和JMS的关系有点类 ...

  7. 运算符.png

  8. 类型转换和类型相关函数.png

  9. LogBack简易教程

    1.简介 LogBack是一个日志框架,它与Log4j可以说是同出一源,都出自Ceki Gülcü之手.(log4j的原型是早前由Ceki Gülcü贡献给Apache基金会的) 1.1 LogBac ...

  10. 在Outlook中查看预览SharePoint文档库的文档

    本文概况 阅读时间: 约2分钟 适用版本:SharePoint Server 2010及以上 面向用户:普通用户,管理员 难度指数:★★☆☆☆ 在日常工作中,总有一些常用的文档需要经常打开查看,其实我 ...