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. Nginx与tomcat组合的简单使用

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 项目中瓦片资源越来越多,如果提高瓦片的访问效率是一个需要解决的 ...

  2. How to implement equals() and hashCode() methods in Java[reproduced]

    Part I:equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and ...

  3. 外边距塌陷之clearance

    在一个BFC中,垂直方向上相邻的块级盒子产生外边距塌陷,本文要说一个特殊的外边距塌陷情况,即当垂直方向上,两个块级盒子之间有个浮动元素相隔时,这个时候会产生什么样的效果呢? .outer{ overf ...

  4. C# 本质论 第二章 数据类型

    浮点数的精度由有效数字的个数决定.除非用分数表示时,分母恰好是2的整数次幂,否则用二进制浮点类型无法准确地表示该数(0.1,表示成分数是1/10,分母10不能用有限二进制表示),二进制浮点类型无法准确 ...

  5. eclipse中Maven运行时报错: -Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.

    1.安装 Maven 如果需要使用到 Maven ,必须首先安装 Maven , Maven 的下载地址在 Apache Maven 中有,您也可以点击这里下载 zip ,tar.gz. 下载好 Ma ...

  6. (原创)解决.net 下使用uploadify,在火狐浏览器下的error 302

    简单粗劣说下哈,通过uploadify中flash在火狐下上传,造成了erroe 302, 是因为其session丢失,并修改了其sessionID. 网上有很多案列,可并没有这么直接.感觉绕了点弯. ...

  7. 【转载】PHP PSR-1 基本代码规范(中文版)

    基本代码规范 本篇规范制定了代码基本元素的相关标准, 以确保共享的PHP代码间具有较高程度的技术互通性. 关键词 "必须"("MUST")."一定不可 ...

  8. 非域客户端的office使用RMS加密服务出现‘介绍“信息权限管理服务”’服务的提示

    环境:office2007,需要使用windows RMS服务,客户机处于工作组模式,如图: 出现这个说明客户机没有发现RMS服务,可以通过导入注册表解决,如下: Windows Registry E ...

  9. Xcode自定义代码块

    到现在才发现原来Xcode有自定义代码块这么神奇的功能,能简化很多无聊的敲重复代码的工作,真是感叹我怎么才知道!!! 具体的设置流程见:http://nshipster.cn/xcode-snippe ...

  10. iOS角度与弧度转换

    在iOS中图片的旋转单位为弧度而不是角度,所以经常会在两者之间进行转换 弧度转角度 #define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / ...