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 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:
|
|
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.
一盘棋,要赢的话,要任意行,列,斜线都是相同的棋子才可以。总共有2n + 2总赢法。行数+列数+正斜线+反斜线。
用一个长为2n * 2的数组,来统计行,列,斜线的棋子出现次数。counter[0, n - 1] 统计行,counter[n, 2n - 1] 统计列,counter[2n]为正斜线,counter[2n + 1]为反斜线。player1下棋,counter + 1, player2下棋, counter - 1。
当下完一步棋的时候,检查当前行,列,或斜线中是否有一个数的绝对值为n. 为n的时候说明player1获胜,为-n的时候说明player2获胜。
|
|
下面是Discuss里看到的最快的做法,虽然比较浪费空间,但是速度很快
|
|
Ref: https://discuss.leetcode.com/topic/44592/7-8-lines-o-1-java-python