[抄题]:
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|
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道怎么表示数学关系:每一行都不能有2种元素。所以必须要rows[row] == row才行
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 对角线元素也不是直接加一的,也要加addon来表示区别
- 反向相加也行,所以最后的结果是绝对值
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
反向相加也行,所以最后的结果是绝对值
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class TicTacToe { private int[] rows; private int[] cols; private int diagnonal; private int antidiagonal; public TicTacToe(int n) { int[] rows = new int[n]; int[] cols = new int[n]; } public int move(int row, int col, int player) { //initialization: add 1 or -1 int addOn = (player == 1) ? 1 : -1; //handle 4 cases rows[row] += addOn; cols[col] += addOn; if (row == col) { diagnonal += addOn; } if (row + col == cols.length - 1) { antidiagonal += addOn; } //exit if element == row int size = rows.length; if (Math.abs(rows[row]) == size || Math.abs(cols[col]) == size || Math.abs(diagnonal) == size || Math.abs(antidiagonal) == size) { return player; } return 0; } }