1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| import java.util.*;
public class DistanceArray { static int[][] POINTS = new int[][]{{}, {}, {}, {}, {}}; static int[][] DISTANCES = new int[POINTS.length][POINTS.length]; static int N, M; static int[][] MOVE = new int[][]{ {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; static int[][] ROUTE = new int[][]{ {0, 1, 2, 3, 4}, {0, 2, 1, 3, 4}, {0, 1, 3, 2, 4}, {0, 3, 1, 2, 4}, {0, 2, 3, 1, 4}, {0, 3, 2, 1, 4} }; static Queue<int[]> QUEUE = new ArrayDeque<>(); static List<int[]> NEXT_ITEMS = new ArrayList<>(); static boolean[][] VISITED; static int MIN;
public static void main(String[] args) { initDistanceArray(); findMin(); System.out.printf("min distance is %d", MIN); }
private static void findMin() { MIN = Integer.MAX_VALUE; for (int[] route : ROUTE) { int distance = 0; boolean arrived = true; for (int i = 1; i < route.length; i++) { int subMin = DISTANCES[route[i]][route[i - 1]]; if (subMin == Integer.MIN_VALUE) { arrived = false; break; } else { distance += subMin; } }
if (arrived) { MIN = Math.min(MIN, distance); } }
if (MIN == Integer.MAX_VALUE) { MIN = -1; } }
private static void initDistanceArray() { for (int start = 0; start < POINTS.length; start++) { int[] stepDis = minDistance(POINTS[start], start + 1); for (int end = start + 1; end < POINTS.length; end++) { DISTANCES[start][end] = stepDis[end]; DISTANCES[end][start] = stepDis[end]; } } }
private static int[] minDistance(int[] start, int idx) { QUEUE.clear(); NEXT_ITEMS.clear(); VISITED = new boolean[N][M];
int calcCount = POINTS.length - idx; int[] resp = new int[POINTS.length]; Arrays.fill(resp, Integer.MIN_VALUE);
QUEUE.offer(start); VISITED[start[0]][start[1]] = true; int step = 0;
while (!QUEUE.isEmpty()) { while (!QUEUE.isEmpty()) { int[] curr = QUEUE.poll();
for (int end = idx; end < POINTS.length; end++) { if (curr[0] == POINTS[end][0] && curr[1] == POINTS[end][1]) { resp[end] = step; calcCount--; } }
if (calcCount == 0) { return resp; }
for (int[] shift : MOVE) { int nx = curr[0] + shift[0]; int ny = curr[1] + shift[1]; if (nx >= 0 && nx < N && ny >= 0 && ny < M) { if (!VISITED[nx][ny]) { VISITED[nx][ny] = true; NEXT_ITEMS.add(new int[]{nx, ny}); } } } }
step++; QUEUE.addAll(NEXT_ITEMS); NEXT_ITEMS.clear(); }
return resp; } }
|