Could you please give me some clue that how a graph can be implemented using adjacency lists/sets and How does it work for directed graphs? Undirected graphs? Weighted graphs?
Consider a directed acyclic graph like this:
1->2
1->3
2->4
2->5
3->6
3->7
Another way to view it is:
1
/ \
2 3
/ \ / \
4 5 6 7
This is really just a small binary tree. An adjacency list representation looks like:
1 -> {2, 3}
2 -> {4, 5}
3 -> {6, 7}
So consider that this could be a HashMap of Integers that point to Sets of Integers.
Now consider that the original graph is undirected, in other words there are parent pointers.
1<->2
1<->3
2<->4
2<->5
3<->6
3<->7
Now the representation needs more entries:
1 -> {2, 3}
2 -> {1, 4, 5}
3 -> {1, 6, 7}
4 -> {2}
5 -> {2}
6 -> {3}
7 -> {3}
Lets return to the directed version of the graph and weight it:
The weights are the first entry in the tuple and the child is the second entry. So it looks like
Parent->(Weight, Child)
.
1->(.9,2)
1->(.1,3)
2->(.9,4)
2->(.1,5)
3->(.5,6)
3->(.5,7)
So 90% of the time we go from 1->2
then 90% of the time that we are at 2 we will go 2->4
.
The representation can look very similar to the directed graph:
1 -> {(.9,2), (.1,3)}
2 -> {(.9,4), (.1,5)}
3 -> {(.5,6), (.5,7)}
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.