public class TicTacToe {
enum State {
NO_WINNER, WINNER_1, WINNER_2
};
public static State checkWinner(int[][] board) {
// Check LINES
for (int i = 0; i < board.length; i++) { // for each line
int sum = 0;
for (int j = 0; j < board[i].length; j++) {
sum += board[i][j];
}
if (sum == board.length) {
return State.WINNER_1;
}
if (sum == -board.length) {
return State.WINNER_2;
}
}
// Check COLUMNS
for (int i = 0; i < board.length; i++) { // for each column
int sum = 0;
for (int j = 0; j < board.length; j++) {
sum += board[j][i];
}
if (sum == board.length) {
return State.WINNER_1;
}
if (sum == -board.length) {
return State.WINNER_2;
}
}
// Check first DIAGONAL
int sum = 0;
for (int i = 0; i < board.length; i++) {
sum += board[i][i];
if (sum == board.length) {
return State.WINNER_1;
}
if (sum == -board.length) {
return State.WINNER_2;
}
}
// Check second DIAGONAL
sum = 0;
for (int i = 0; i < board.length; i++) {
sum += board[i][board.length - i - 1];
if (sum == board.length) {
return State.WINNER_1;
}
if (sum == -board.length) {
return State.WINNER_2;
}
}
return State.NO_WINNER;
}
public static void main(String[] args) {
System.out.println(checkWinner(new int[][] { { 1, 1, 1 }, { 0, 0, 0 },{ 0, 0, 0 } }));
System.out.println(checkWinner(new int[][] { { -1, 0, 0 },{ -1, 0, 0 }, { -1, 0, 0 } }));
System.out.println(checkWinner(new int[][] { { 1, 0, 0 }, { 0, 1, 0 },{ 0, 0, 1 } }));
System.out.println(checkWinner(new int[][] { { 0, 0, -1 }, { 0, -1, 0 },{ -1, 0, 0 } }));
System.out.println(checkWinner(new int[][] { { 1, 0, 0 }, { 0, 0, 0 },{ 0, 0, 1 } }));
}
}
试着看一下:http://stackoverflow.com/questions/1056316/algorithm-for-determining-tic-tac-toe-game-over – sshashank124
@ sshashank124我已经做到了。但是不明白。 –
他们已经做到了这一点(我更喜欢这种方法)的方式是他们传递新添加的标记的坐标。这样,他们只需检查包含该位置的可能的行和列。这比每次检查整个板块要好 – sshashank124