# Moderate 判断井字游戏的胜利 @CareerCup

package Moderate;

/**
* Design an algorithm to figure out if someone has won in a game of tic-tac-toe.

*
*/
public class S17_2 {

// 方法一：如果HasWon函数需要被频繁调用
public static int convertBoardToInt(char[][] board) {
int factor = 1;
int sum = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
int v = 0;
switch(board[i][j]){
case 'x':
v = 1;
break;
case 'o':
v = 2;
break;
default:
v = 0;
}

sum += v * factor;
factor *= 3;
}
}
return sum;
}

// 方法二：如果HasWon函数只被调用一次或很少次
public static char hasWon(char[][] board){
int type = 0;
int N = board.length;

int i, j;

// 对每一行都检查
for(i=0; i<N; i++){
if(board[i][0] != ' '){
for(j=1; j<N; j++){
if(board[i][j] != board[i][j-1]){
break;
}
}
if(j == N){
return board[i][0];
}
}
}

// 对每一列都检查
for(j=0; j<N; j++){
if(board[0][j] != ' '){
for(i=1; i<N; i++){
if(board[i][j] != board[i-1][j]){
break;
}
}
if(i == N){
return board[0][j];
}
}
}

// 正对角线检查（左上到右下）
if(board[0][0] != ' '){
for(i=1; i<N; i++){
if(board[i][i] != board[i-1][i-1]){
break;
}
}
if(i == N){
return board[0][0];
}
}

// 逆对角线检查（左下到右上）
if(board[N-1][0] != ' '){
for(i=1; i<N; i++){
if(board[N-i-1][i] != board[N-i][i-1]){
break;
}
}
if(i == N){
return board[N-1][0];
}
}

return ' ';
}

public static void main(String[] args) {
char[][] board = {
{'x', 'x', 'o'},
{' ', 'x', ' '},
{' ', ' ', 'x'}};

int v = convertBoardToInt(board);
System.out.println(v);

char result = hasWon(board);
if(result == ' '){
System.out.println("No one won!");
}else{
System.out.println(result + " has won");
}

}

}


举报原因： 您举报文章：Moderate 判断井字游戏的胜利 @CareerCup 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)