资讯专栏INFORMATION COLUMN

348. Design Tic-Tac-Toe

zhkai / 2727人阅读

摘要:当有一行完全只有这两个中的其中一个人时,的绝对值应该等于这个数列的长度,这样就不需要每次再扫一遍数组。

题目:
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.
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() operation?

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.

解答:
一开始其实就想到了hint, 作出了下面的解法:

public class TicTacToe {
    int[][] grid;
    int n;
    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        grid = new int[n][n];
        this.n = n;
    }
    
    public boolean check(int row, int col, int len) {
        boolean hori = true, verti = true, diag1 = true, diag2 = true;
        //check horizontal
        for (int i = 0; i < len - 1; i++) {
            if (grid[row][i] != grid[row][i + 1]) {
                hori = false;
            }
        }
        //check vertical
        for (int j = 0; j < len - 1; j++) {
            if (grid[j][col] != grid[j + 1][col]) {
                verti = false;
            }
        }
        //check diagonals
        if (row == col) {
            for (int i = 0; i < len - 1; i++) {
                if (grid[i][i] != grid[i + 1][i + 1]) {
                    diag1 = false;
                }
            }
        } else {
            diag1 = false;
        }
        
        if (row + col == len - 1) {
            for (int i = 0; i < len - 1; i++) {
                if (grid[i][len - 1 - i] != grid[i + 1][len - 2 - i]) {
                    diag2 = false;
                }
            }
        } else {
            diag2 = false;
        }
        return hori || verti || diag1 || diag2;
    }
    
    /** 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) {
        grid[row][col] = player;
        if (check(row, col, n)) return player;
        return 0;
    }
}

这个解法冗余在check行个列的时候,每一次都要再扫一遍这一行这一列,所以如果只有两个player,可以把这两个player记作1, -1。当有一行完全只有这两个player中的其中一个人时,sum的绝对值应该等于这个数列的长度,这样就不需要每次再扫一遍数组。代码如下:

public class TicTacToe {
    int[] rows, cols;
    int diagonal, antiDiagonal;
    int len;
    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        rows = new int[n];
        cols = new int[n];
        this.len = 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;
        //Every time we only do adding, dont need to re-scan the whole line
        int toAdd = player == 1 ? 1 : -1;
        rows[row] += toAdd;
        cols[col] += toAdd;
        if (row == col) diagonal += toAdd;
        if (row == len - 1 - col) antiDiagonal += toAdd;
        if (Math.abs(rows[row]) == len || Math.abs(cols[col]) == len || Math.abs(diagonal) == len || Math.abs(antiDiagonal) == len) {
            return player;
        }
        return 0;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64930.html

相关文章

  • 348. Design Tic-Tac-Toe

    摘要:题目链接这道题找是否有赢的方法和相似,稍微简化了。统计行列和两个对角线的情况,两个分别用和来记。然后判断是否有一个人赢只需要的复杂度。当然这么做的前提是假设所有的都是的,棋盘一个地方已经被占用了,就不能走那个地方了。 348. Design Tic-Tac-Toe 题目链接:https://leetcode.com/problems... 这道题找是否有player赢的方法和N-Que...

    betacat 评论0 收藏0
  • [LeetCode] 348. Design Tic-Tac-Toe

    Problem 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 winnin...

    MobService 评论0 收藏0
  • Minimax 和 Alpha-beta 剪枝算法简介,以及以此实现的井字棋游戏(Tic-tac-t

    摘要:我们在前文中考虑的那张图就来自这篇文章,之后我们会用剪枝算法来改进之前的解决方案。剪枝算法的实现接下来讨论如何修改前面实现的算法,使其变为剪枝算法。现在我们已经有了现成的和剪枝算法,只要加上一点儿细节就能完成这个游戏了。 前段时间用 React 写了个2048 游戏来练练手,准备用来回顾下 React 相关的各种技术,以及试验一下新技术。在写这个2048的过程中,我考虑是否可以在其中加...

    wemall 评论0 收藏0
  • Minimax 和 Alpha-beta 剪枝算法简介,以及以此实现的井字棋游戏(Tic-tac-t

    摘要:我们在前文中考虑的那张图就来自这篇文章,之后我们会用剪枝算法来改进之前的解决方案。剪枝算法的实现接下来讨论如何修改前面实现的算法,使其变为剪枝算法。现在我们已经有了现成的和剪枝算法,只要加上一点儿细节就能完成这个游戏了。 前段时间用 React 写了个2048 游戏来练练手,准备用来回顾下 React 相关的各种技术,以及试验一下新技术。在写这个2048的过程中,我考虑是否可以在其中加...

    Eirunye 评论0 收藏0
  • 一次诡异的docker错误调试

    摘要:源自小伙伴的求助,虽然没能定位到最终的原因,调试的过程也比较有意思缘起小伙伴求助我,同一个镜像在测试机器上可以运行,在阿里云上运行提示用户不存在。 源自小伙伴的求助,虽然没能定位到最终的原因,调试的过程也比较有意思 缘起 小伙伴求助我,同一个docker镜像在测试机器上可以运行,在阿里云上运行提示用户不存在。 在阿里云上运行提示如下: # docker run --rm -it ima...

    Jeff 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<