public static void main(String[] args) { ArrayList list = new ArrayList(); Scanner in = new Scanner(System.in); System.out.print("please input the number of knight :"); int n = in.nextInt(); for (int i = 0; i < n; i++) { System.out.print("please input the number " + i + " 's position :"); int pos_i = in.nextInt(); int pos_j = in.nextInt(); list.add(new Knight(new Position(pos_i, pos_j))); } int[][] days = new int[Knight.N][Knight.N]; int[][] tot_days = new int[Knight.N][Knight.N]; int[] min = new int[Knight.N * Knight.N]; int[] pos_i = new int[Knight.N * Knight.N]; int[] pos_j = new int[Knight.N * Knight.N]; int index = 0; min[index] = 12345; for (int i = 0; i < Knight.N; i++) for (int j = 0; j < Knight.N; j++) { days[i][j] = 0; tot_days[i][j] = 0; for (int num = 0; num < list.size(); num++) { if (list.get(num).getChess(i, j) > days[i][j]) days[i][j] = list.get(num).getChess(i, j); tot_days[i][j] += list.get(num).getChess(i, j); } if (days[i][j] < min[index]) { index = 0; min[index] = days[i][j]; pos_i[index] = i; pos_j[index] = j; } else if (days[i][j] == min[index]) { min[++index] = days[i][j]; pos_i[index] = i; pos_j[index] = j; } } int po = 0; while (min[0] == min[po]) { System.out.println("use the least days in " + min[po] + " at " + pos_i[po] + "," + pos_j[po] + "with " + tot_days[pos_i[po]][pos_j[po]] + " foots"); po++; } } }
class Knight { public static final int N = 8; private static final Position[] orient = { new Position(-1, -2), new Position(-2, -1), new Position(-2, 1), new Position(-1, 2), new Position(1, 2), new Position(2, 1), new Position(2, -1), new Position(1, -2) }; private int[][] chess; private Queue queue = new LinkedList();
public Knight(Position now) { chess = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) chess[i][j] = -1; queue.add(now); traverseChess(); }
private void traverseChess() { Position p; while ((p = queue.poll()) != null) { chess[p.i][p.j] = p.level; for (int i = 0; i < 8; i++) { Position temp_p = new Position(p.i + orient[i].i, p.j + orient[i].j); if (temp_p.i >= 0 && temp_p.i < N && temp_p.j >= 0 && temp_p.j < N && chess[temp_p.i][temp_p.j] == -1) { temp_p.level = p.level + 1; queue.add(temp_p); } } } }
public int getChess(int i, int j) { return chess[i][j]; } }
class Position { public Position(int i, int j) { this.i = i; this.j = j; }
public int level = 0; public int i; public int j; }