|
| 1 | +// WeightedGraph.java |
| 2 | +// From Classic Computer Science Problems in Java Chapter 4 |
| 3 | +// Copyright 2020 David Kopec |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +// you may not use this file except in compliance with the License. |
| 7 | +// You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, software |
| 12 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +// See the License for the specific language governing permissions and |
| 15 | +// limitations under the License. |
| 16 | + |
1 | 17 | package chapter4;
|
2 | 18 |
|
3 | 19 | import java.util.Arrays;
|
@@ -52,7 +68,10 @@ public static double totalWeight(List<WeightedEdge> path) {
|
52 | 68 | // *start* is the vertex index to start the search at
|
53 | 69 | public List<WeightedEdge> mst(int start) {
|
54 | 70 | LinkedList<WeightedEdge> result = new LinkedList<>(); // final mst
|
55 |
| - PriorityQueue<WeightedEdge> pq = new PriorityQueue(); |
| 71 | + if (start < 0 || start > (getVertexCount() - 1)) { |
| 72 | + return result; |
| 73 | + } |
| 74 | + PriorityQueue<WeightedEdge> pq = new PriorityQueue<>(); |
56 | 75 | boolean[] visited = new boolean[getVertexCount()]; // where we've been
|
57 | 76 |
|
58 | 77 | // this is like a "visit" inner function
|
@@ -133,6 +152,7 @@ public DijkstraResult dijkstra(V root) {
|
133 | 152 | for (WeightedEdge we : edgesOf(u)) {
|
134 | 153 | // the old distance to this vertex
|
135 | 154 | double distV = distances[we.v];
|
| 155 | + // the new distance to this vertex |
136 | 156 | double pathWeight = we.weight + distU;
|
137 | 157 | // new vertex or found shorter path?
|
138 | 158 | if (!visited[we.v] || (distV > pathWeight)) {
|
|
0 commit comments