|
| 1 | +public static String WeightedPath(String[] strArr) { |
| 2 | + int n = Integer.parseInt(strArr[0]); |
| 3 | + String[] nodes = new String[n]; |
| 4 | + for (int i = 0; i < n; i++) { |
| 5 | + nodes[i] = strArr[i + 1]; |
| 6 | + } |
| 7 | + Map<String, Map<String, Integer>> graph = new HashMap<>(); |
| 8 | + for (int i = n + 1; i < strArr.length; i++) { |
| 9 | + String[] edge = strArr[i].split("\\|"); |
| 10 | + String from = edge[0]; |
| 11 | + String to = edge[1]; |
| 12 | + int weight = Integer.parseInt(edge[2]); |
| 13 | + graph.putIfAbsent(from, new HashMap<>()); |
| 14 | + graph.putIfAbsent(to, new HashMap<>()); |
| 15 | + graph.get(from).put(to, weight); |
| 16 | + graph.get(to).put(from, weight); |
| 17 | + } |
| 18 | + Map<String, Integer> dist = new HashMap<>(); |
| 19 | + Map<String, String> prev = new HashMap<>(); |
| 20 | + for (String node : nodes) { |
| 21 | + dist.put(node, Integer.MAX_VALUE); |
| 22 | + prev.put(node, null); |
| 23 | + } |
| 24 | + dist.put(nodes[0], 0); |
| 25 | + PriorityQueue<String> pq = new PriorityQueue<>(Comparator.comparingInt(dist::get)); |
| 26 | + pq.add(nodes[0]); |
| 27 | + while (!pq.isEmpty()) { |
| 28 | + String node = pq.poll(); |
| 29 | + if (node.equals(nodes[n - 1])) { |
| 30 | + break; |
| 31 | + } |
| 32 | + try{ |
| 33 | + for (Map.Entry<String, Integer> entry : graph.get(node).entrySet()) { |
| 34 | + String neighbor = entry.getKey(); |
| 35 | + int weight = entry.getValue(); |
| 36 | + int newDist = dist.get(node) + weight; |
| 37 | + if (newDist < dist.get(neighbor)) { |
| 38 | + dist.put(neighbor, newDist); |
| 39 | + prev.put(neighbor, node); |
| 40 | + pq.add(neighbor); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + }catch (NullPointerException e){ |
| 45 | + return "-1"; |
| 46 | + } |
| 47 | + |
| 48 | + } |
| 49 | + if (dist.get(nodes[n - 1]) == Integer.MAX_VALUE) { |
| 50 | + return "-1"; |
| 51 | + } |
| 52 | + StringBuilder sb = new StringBuilder(); |
| 53 | + String node = nodes[n - 1]; |
| 54 | + while (node != null) { |
| 55 | + sb.insert(0, node); |
| 56 | + node = prev.get(node); |
| 57 | + if (node != null) { |
| 58 | + sb.insert(0, "-"); |
| 59 | + } |
| 60 | + } |
| 61 | + return sb.toString(); |
| 62 | + } |
0 commit comments