![]() |
VOOZH | about |
In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph.
We use two STL containers to represent graph:
The idea is to use a vector of pair vectors. Below code implements the same.
Node 0 makes an edge with Node 1 with edge weight =10 Node 4 with edge weight =20 Node 1 makes an edge with Node 0 with edge weight =10 Node 2 with edge weight =30 Node 3 with edge weight =40 Node 4 with edge weight =50 Node 2 makes an edge with Node 1 with edge weight =30 Node 3 with edge weight =60 Node 3 makes an edge with Node 1 with edge weight =40 Node 2 with edge weight =60 Node 4 with edge weight =70 Node 4 makes an edge with Node 0 with edge weight =20 Node 1 with edge weight =50 Node 3 with edge weight =70
Complexity analysis :
Time complexity: O(1), as it takes a constant amount of time to add a new HashMap object to an ArrayList. The time complexity of printing the graph is O(V * E), as it takes O(E) time to print the edges for each vertex, and there are V vertices in the graph.
Auxiliary Space: O(V + E), where V is the number of vertices in the graph and E is the number of edges. This is because the adjacency list uses an ArrayList of ArrayLists to store the graph, and each ArrayList and HashMap object consumes a constant amount of space.
and improved by Kunal Verma