Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
private static int[] table;
private static int convertBoardToInt(String inp, int n) {
int n2 = n * n;
int sum = 0;
int[] board = new int[n2];
for (int i = 0; i < n2; i++) {
if(hasWon(sum) != 0) return sum;
int p = i % 2 + 1;
int d = Integer.parseInt(inp.substring(i, i+1), 16);
if(n == 3) d--;
if (board[d] != 0) return -p;
else board[d] = p;
sum += p * (int)Math.pow(3, d);
}
return sum;
}
private static int[] hashToIntArray(int h, int n) {
int n2 = n * n;
int[] a = new int[n2];
for(int i = 0; i < n2; i++) {
a[i] = h % 3;
h /= 3;
}
return a;
}
private static void setResults(int n) {
int size = table.length;
for(int h = 0; h < size; h++) {
setResult(h, n);
}
}
private static void setResult(int h, int n) {
int[] a = hashToIntArray(h, n);
/* row */
for(int i = 0; i < n; i++) {
int p = i * n;
if (a[p] != 0) {
boolean flg = true;
for(int j = 1; j < n; j++)
flg &= a[p] == a[p + j];
if(flg) {
table[h] = a[p];
return;
}
}
}
/* column */
for(int i = 0; i < n; i++) {
if (a[i] != 0) {
boolean flg = true;
for(int j = 1; j < n; j++)
flg &= a[i] == a[i + j*n];
if(flg) {
table[h] = a[i];
return;
}
}
}
/* diagonal */
if (a[0] != 0) {
boolean flg = true;
for(int i = 1; i < n; i++) {
flg &= a[0] == a[i + i * n];
}
if(flg) {
table[h] = a[0];
return;
}
}
/* diagonal2 */
if (a[n-1] != 0) {
boolean flg = true;
for(int i = 1; i < n; i++) {
flg &= (a[n-1] == a[(n-1) * (i + 1)]);
}
if(flg) {
table[h] = a[n-1];
return;
}
}
}
private static int hasWon(int h) {
return table[h];
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
table = new int[(int)Math.pow(3, n*n)];
setResults(n);
while((line = br.readLine()) != null) {
String[] ss = line.split("\\t");
int v = convertBoardToInt(ss[1], n);
String result = null;
if(v < 0) {
result = String.format("Foul : %s won.", (-v == 1)? "x": "o");
} else {
switch(hasWon(v)) {
case 0: result = "Draw game."; break;
case 1: result = "o won."; break;
case 2: result = "x won."; break;
}
}
if(!result.equals(ss[2])) {
System.out.println("input:" + ss[1]);
System.out.println("expected:" + ss[2]);
System.out.println("actual:" + result);
}
}
}
}