Graph
Last updated
Last updated
A graph is a set of values that are related. There are connections (edges) to different nodes (vertex) in a graph.
There are 3 things to take note in a graph:
Directed vs Undirected. Undirected means I can go back and forth between nodes, like Facebook friends. Directed means I can only go in a specific direction, like Twitter where you follow, but the other person does not automatically follow you
Weighted vs Unweighted. Weighted means, besides value in the node, we can also have information on the edges. These sort of graphs are used a lot in calculating optimal paths / fastest way to destination.
Cyclic vs acyclic. Cyclic is the idea where the nodes are all interconnected and the idea is you can go back to the start
There are 3 different ways to represent graph:
Edge List - simply shows the connection
Adjacent List - create a graph where the index is the node and the value is the nodes neighbors
Adjacent Matrix - the matrix is going to have zeros and ones indicating whether the node X has a connection to node Y. Zero means no connection and One means yes. And if you have a weighted graph, you can actually add weights here, instead of 1 and 0.
In the graph exercise, it is more useful to use object rather than array. Remember shifting on array is expensive. With objects we can quickly find items.
Pro of Graph: There are relationships
Cons of Graph: They can get complicated, thus scaling is hard