题目
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.
答案
class TicTacToe {
Map<String, int[]> map;
int n;
/** Initialize your data structure here. */
public TicTacToe(int n) {
map = new HashMap<>();
this.n = 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) {
// Placing a piece on board[row][col] affects 1 row, 1 col, and 0/1/2 diagonals
String k1 = "r" + Integer.toString(row);
String k2 = "c" + Integer.toString(col);
String k3 = "", k4 = "";
int[] r_cnt = map.get(k1);
if(r_cnt == null) {
r_cnt = new int[2];
map.put(k1, r_cnt);
}
r_cnt[player - 1]++;
int[] c_cnt = map.get(k2);
if(c_cnt == null) {
c_cnt = new int[2];
map.put(k2, c_cnt);
}
c_cnt[player - 1]++;
if(row == col) {
k3 = "d1#";
int[] d1_cnt = map.get(k3);
if(d1_cnt == null) {
d1_cnt = new int[2];
map.put(k3, d1_cnt);
}
d1_cnt[player - 1]++;
}
if(row == this.n - col - 1) {
k4 = "d2#";
int[] d2_cnt = map.get(k4);
if(d2_cnt == null) {
d2_cnt = new int[2];
map.put(k4, d2_cnt);
}
d2_cnt[player - 1]++;
}
// Check if end condition is met
return check();
}
private int check() {
for(Map.Entry<String, int[]> entry : map.entrySet()) {
String k = entry.getKey();
int[] cnt = entry.getValue();
if(cnt[0] == this.n) return 1;
if(cnt[1] == this.n) return 2;
}
return 0;
}
}
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/
网友评论