Find Winner on a Tic Tac Toe Game
给一个数组是一些moves, 求三连游戏的胜者。
class Solution {
public String tictactoe(int[][] moves) {
int[][] g = new int[3][3];
int cc = 0;
for(int[] m : moves){
if(cc % 2 == 0)
g[m[0]][m[1]] = 1;
else
g[m[0]][m[1]] = -100;
cc++;
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++) {
int r = checkRow(g, j);
int c = checkCol(g, i);
int d = checkDia(g, i, j);
int dd = checkDDia(g, i, j);
if(r == 3)
return "A";
if(r == -300)
return "B";
if(c == 3)
return "A";
if(c == -300)
return "B";
if(d == 3)
return "A";
if(d == -300)
return "B";
if(dd == 3)
return "A";
if(dd == -300)
return "B";
}
}
return cc == 9 ? "Draw" : "Pending";
}
private int checkRow(int[][] g, int j) {
int res = 0;
for(int i = 0; i < 3; i++){
res += g[i][j];
}
return res;
}
private int checkCol(int[][] g, int i) {
int res = 0;
for(int j = 0; j < 3; j++){
res += g[i][j];
}
return res;
}
private int checkDia(int[][] g, int i, int j) {
if(i != 1 || j != 1)
return 0;
int res = 0;
for(int k = 0; k < 3; k++){
res += g[k][k];
}
return res;
}
private int checkDDia(int[][]g, int i, int j){
if(i != 1 || j != 1)
return 0;
int res = 0;
i = 0;
j = 2;
for(int k = 0; k < 3; k++){
res += g[i++][j--];
}
return res;
}
}