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:
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
这个解法冗余在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;}
}
关键字:java, leetcode
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!