I have a list Graph
, consisting of Node
-Maps:
public static Map<Integer, List<Integer>> node = new HashMap<>();
public static List<HashMap> graph = new ArrayList<>();
In each Node
-Map I want to save the ID as Integer
and the adjecent nodes in an adjecency-list as List<Integer>
I create the Nodes with the following function:
public static void addNode(int id){
graph.add( (HashMap) node.put(id, new ArrayList<>()) );
}
My question is: how can I change the adjacency-lists inside of a special node and add Integers
to them. I don't understand how I can address them. I tried this, but it is not working:
public static void addVertice(int k, int v){
graph.get(k).put( k, add(v) );
}
(So I want to add (Integer) v into the list of the Node-Map with the key k)
CodePudding user response:
The collections you are trying to use for storing graph looks redundant. You can create single collection to hold the graph in the form of adjacency lists with each node as key and each node's adjacency list as value.
public static Map<Integer, List<Integer>> graph = new HashMap<>();
public static void addNode(int node){
graph.put(node, new ArrayList<>());
}
public static void addEdge(int fromNode, int toNode){
graph.get(fromNode).add(toNode);
}
Also, for undirected graph, you can use following code.
public static Map<Integer, List<Integer>> graph = new HashMap<>();
public static void addNode(int node){
graph.put(node, new ArrayList<>());
}
public static void addEdge(int fromNode, int toNode){
graph.get(fromNode).add(toNode);
graph.get(toNode).add(fromNode);
}