[2016.4][京東暑期實習筆試]三子棋

yoohoosome發表於2016-04-08

package bupt.syh;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			char[][] inputMx = new char[3][3];
			for (int i = 0; i < 3; i++) {
				String line = in.nextLine();
				for (int j = 0; j < 3; j++) {
					inputMx[i][j] = line.charAt(j);
				}
			}
			// 是否有人win
			int someoneWon = isSomeoneWon(inputMx);
			if (someoneWon == 1) {
				System.out.println("1 won");
				continue;
			} else if (someoneWon == 2) {
				System.out.println("2 won");
				continue;
			}
			
			// 該誰下了
			int count[] = count(inputMx);
			if (count[0] == 5 && count[1] == 4) {
				System.out.println("Draw");
			} else if (count[0] == count[1]) {
				System.out.println("1");
			} else if (count[0] == count[1] + 1) {
				System.out.println("2");
			} else {
				System.out.println("x");
			}		
			
		}
	}
	
	public static int isSomeoneWon (char[][] mx) {
		for (int i = 0; i < 3; i++) {
			if (mx[i][0] == mx[i][1] && mx[i][0] == mx[i][2]) {
				if (mx[i][0] == 'X') {
					return 1;
				} else if (mx[i][0] == 'O') {
					return 2;
				}
			}
		}
		for (int i = 0; i < 3; i++) {
			if (mx[0][i] == mx[1][i] && mx[0][i] == mx[2][i]) {
				if (mx[0][i] == 'X') {
					return 1;
				} else if (mx[0][i] == 'O') {
					return 2;
				}
			}
		}
		if (mx[0][0] == mx[1][1] && mx[0][0] == mx[2][2]) {
			if (mx[0][0] == 'X') {
				return 1;
			} else if (mx[0][0] == 'O') {
				return 2;
			}
		}
		if (mx[2][0] == mx[1][1] && mx[2][0] == mx[0][2]) {
			if (mx[1][1] == 'X') {
				return 1;
			} else if (mx[1][1] == 'O') {
				return 2;
			}
		}
		return 0;
	}
	
	public static int[] count(char[][] mx) {
		int[] rst = new int[2];
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				if (mx[i][j] == 'X') {
					rst[0]++;
				} else if (mx[i][j] == 'O') {
					rst[1]++;
				}
			}
		}
		return rst;
	}
}


相關文章