I am using adjacency lists to represent a directed weighted graph and based on the example code provided by this SO question, I have created the following:
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class _Graph {
private Map<String, LinkedHashSet<HashMap<String, Integer>>> map = new HashMap<String, LinkedHashSet<HashMap<String, Integer>>>();
public void addEdge(String node1, String node2, int dist) {
LinkedHashSet<HashMap<String, Integer>> adjacent = map.get(node1);
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
if(adjacent==null) {
adjacent = new LinkedHashSet<HashMap<String, Integer>>();
map.put(node1, adjacent);
}
innerMap.put(node2, dist);
adjacent.add(innerMap);
}
public boolean isConnected(String node1, String node2) {
Set<HashMap<String, Integer>> adjacent = map.get(node1);
if(adjacent==null) {
return false;
}
return adjacent.contains(node2);
}
public LinkedList<HashMap<String, Integer>> adjacentNodes(String node) {
LinkedHashSet<HashMap<String, Integer>> adjacent = map.get(node);
if(adjacent==null) {
return new LinkedList<HashMap<String, Integer>>();
}
return new LinkedList<HashMap<String, Integer>>(adjacent);
}
}
I am having trouble making the isConnected
method to work properly. Am I using a wrong data structure to represent the graph here (Map<String, LinkedHashSet<HashMap<String, Integer>>>
)? The hashmap will hold the name of the connected node and the distance to it:
Map<startNode, LinkedHashSet<HashMap<endNode, distanceToEndNode>>>
- Basically how can I check if a node
belongs to the adjacency list of a
given base node? I think the problem
is reduced to iterating properly
over the
adjacent
Set<HashMap<String, Integer>>
structure, or is my reasoning wrong? - In my second method
adjacentNodes(String node)
I am returning a linked list containing the maps (in a set structure) of the connected nodes and their distances. How could I efficiently iterate to see all connections of a any given node?