mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
更新0094.城市间货物运输I.md Java版本解法
This commit is contained in:
@ -392,6 +392,63 @@ Bellman_ford 是可以计算 负权值的单源最短路算法。
|
|||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
### Java
|
### Java
|
||||||
|
```Java
|
||||||
|
public class Main {
|
||||||
|
|
||||||
|
// Define an inner class Edge
|
||||||
|
static class Edge {
|
||||||
|
int from;
|
||||||
|
int to;
|
||||||
|
int val;
|
||||||
|
public Edge(int from, int to, int val) {
|
||||||
|
this.from = from;
|
||||||
|
this.to = to;
|
||||||
|
this.val = val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// Input processing
|
||||||
|
Scanner sc = new Scanner(System.in);
|
||||||
|
int n = sc.nextInt();
|
||||||
|
int m = sc.nextInt();
|
||||||
|
List<Edge> edges = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int i = 0; i < m; i++) {
|
||||||
|
int from = sc.nextInt();
|
||||||
|
int to = sc.nextInt();
|
||||||
|
int val = sc.nextInt();
|
||||||
|
edges.add(new Edge(from, to, val));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Represents the minimum distance from the current node to the original node
|
||||||
|
int[] minDist = new int[n + 1];
|
||||||
|
|
||||||
|
// Initialize the minDist array
|
||||||
|
Arrays.fill(minDist, Integer.MAX_VALUE);
|
||||||
|
minDist[1] = 0;
|
||||||
|
|
||||||
|
// Starts the loop to relax all edges n - 1 times to update minDist array
|
||||||
|
for (int i = 1; i < n; i++) {
|
||||||
|
|
||||||
|
for (Edge edge : edges) {
|
||||||
|
// Updates the minDist array
|
||||||
|
if (minDist[edge.from] != Integer.MAX_VALUE && (minDist[edge.from] + edge.val) < minDist[edge.to]) {
|
||||||
|
minDist[edge.to] = minDist[edge.from] + edge.val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outcome printing
|
||||||
|
if (minDist[n] == Integer.MAX_VALUE) {
|
||||||
|
System.out.println("unconnected");
|
||||||
|
} else {
|
||||||
|
System.out.println(minDist[n]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
### Python
|
### Python
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user