Question

I'm trying to create a undirected graph, so i used the code below to create a graph after execution the output i get is :

{1=[2, 5, 10, 18], 
 2=[1, 3], 3=[2, 4], 
 4=[3, 5], 5=[1, 4, 6], 
 6=[5, 7], 7=[6, 8], 
 8=[7, 9], 9=[8], 10=[1, 11], 
 11=[10, 12, 13, 11, 11], 
 12=[11, 19], 13=[11], 
 19=[12], 18=[1], 
 21=[22], 22=[21]}

Now i try to implement BFS to find shortest path. My question is : Is it possible to use the hashmap to implement bfs if it is possible how can i do it? or it is not possible which method should i use instead of hashmap.

Map<Integer, ArrayList<Integer>> adj;

public Graph(ArrayList<String> nodes) {
    adj = new HashMap<Integer, ArrayList<Integer>>();
    for (int i = 0; i < nodes.size(); ++i) {
        adj.put(Integer.parseInt(nodes.get(i)), new ArrayList<Integer>());
        }
    }

public void addNeighbor(int v1, int v2) {
    adj.get(v1).add(v2);
}
Was it helpful?

Solution

Is it possible to use the hashmap to implement bfs if it is possible how can i do it? or it is not possible which method should i use instead of hashmap.

Yes it's possible. You are working with an adjacency list. To implement a BFS you will need a queue (there an interface in Java for this). To traverse the graph you start with a single node in your queue, and while this queue is not empty you get the next node and add all the adjacent nodes into your queue, here is where you will need to access your Map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top