I am trying to solve a problem where I need to find the max distance between 2 points in a graph. I wrote this code for implementing Dijkstra's algorithm (obviously by changing the minimization to maximization), but it doesn't seem to work in some cases, and I am unable to figure out the unhandled case. Can anyone help me in pointing out what am I missing in my implementation or if something is inherently incorrect?
public double maxDistance(int n, int start, int end) {
Map<Integer, List<Integer>> adjacencyList = getAdjacencyList(); // Adj. list in form of HashMap
Map<String, Double> distanceMap = getDistanceMap(); // <Edge, Double> (value is distance)
Queue<Integer> bfsQueue = new LinkedList<>(); // queue to do a BFS
boolean[] visited = new boolean[n];
double[] distance = new double[n];
bfsQueue.add(start);
while (!bfsQueue.isEmpty()) {
int node = bfsQueue.poll();
List<Integer> neighbors = adjacencyList.getOrDefault(node, new ArrayList<>());
for (int neighbor: neighbors) {
if (visited[neighbor]) continue;
bfsQueue.add(neighbor);
double edgeLength = distanceMap.get(new Edge(node, neighbor));
double newLength = distance[node] + edgeLength;
if (newLength > distance[neighbor]) {
distance[neighbor] = newLength;
}
}
visited[node] = true;
}
return distance[end];
}
Edge, it's hard to judge ifdistanceMap.get(new Edge(...))works as expected. Did you correctly overwriteEdge.equals()andEdge.hashCode()?