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.
Follow up:
Could you do better than O(n2) per move() operation?
解法1: O(N) move
基本的思路就是每次move之后,检查行,列,对角线是否满足胜利条件,如果满足就返回。
|
|
解法2: O(1) move
实际上这题可以做到o(1)的复杂度。用+1和-1表示每一个方向两个选手的落子情况。那么如果一个行都被其中一个选手占领,他的绝对值就一定和行数相等。由此
|
|