ccf csf 201803-4 棋局評估
import java.util.ArrayList; import java.util.List; import java.util.Scanner;
class Main {
static int num = 0; static int[][] qp; public static Scanner sc = new Scanner(System.in);
static class Point { int x, y;
public Point(int x, int y) { super(); this.x = x; this.y = y; } }
static final int A = 1, B = 2;
public static void main(String[] args) { num = sc.nextInt(); qp = new int[3][3]; for (int i = 0; i < num; i++) {
for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { qp[j][k] = sc.nextInt(); } } System.out.println(do_work(A)); } }
private static int check() { // row for (int i = 0; i < 3; i++) { if (qp[i][0] == qp[i][1] && qp[i][1] == qp[i][2] && qp[i][1] > 0) { return qp[i][1]; } } // cel for (int i = 0; i < 3; i++) { if (qp[0][i] == qp[1][i] && qp[1][i] == qp[2][i] && qp[1][i] > 0) { return qp[0][i]; } } if (qp[0][0] == qp[1][1] && qp[1][1] == qp[2][2] && qp[1][1] > 0) { return qp[1][1]; } if (qp[0][2] == qp[1][1] && qp[1][1] == qp[2][0] && qp[1][1] > 0) { return qp[1][1]; } return 0; }
private static ArrayList<Point> okLocation() { ArrayList<Point> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (qp[i][j] == 0) { list.add(new Point(i, j)); } } } return list; }
private static int do_work(int player) { int win = check();// 是否結束 if (win == A) { return grade(); } else if (win == B) return -grade();
if (player == A) { int grade = Integer.MIN_VALUE; List<Point> list = okLocation(); if (list.isEmpty()) return 0; for (Point point : list) { qp[point.x][point.y] = A; grade = Math.max(grade, do_work(B)); qp[point.x][point.y] = 0; } return grade; } else { int grade = Integer.MAX_VALUE; List<Point> list = okLocation(); if (list.isEmpty()) return 0; for (Point point : list) { qp[point.x][point.y] = B; grade = Math.min(grade, do_work(A)); qp[point.x][point.y] = 0; } return grade; } }
private static int grade() { int grade = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (qp[i][j] == 0) { grade++; } } } return grade; } }