Graph is the relationship between each nodes. For example:
On Facebook which indicated by the lines between us. So all of us is the vertexs in graph and the lines are edges. To be more precisly, Graph is a Data Structure form by the set of vertexs and edges.
Let's discuss the following problems:
With the real life examples above, we can deal with plenty of problems through graph theoroy(algorithm).
There are no direction for each edges.
Each edges has specific direction
Each edge has its own weight
There exist at least a cycle in digraph or undirected graph
Using container to store both vertexs and edges
In this example, I will use adjacency matrix to represent the graph
Go as deep as one node can!
For example, we start from node a.
We then explore other node connected to node a. Next node is c. Change our position from a to c.
Check the node connected to c. The first node we would encounter was a, however, a had already been visited. Therefore, we move next to b.
Check the node connected to b. There are no avaliable nodes for b because a had been already visited. Move back to c
Visit node d.
Alredy visited c and a. No node to visit from d. Move back to c.
No more node to visit from c. Move back to a.
No more node to visit from a. Stop program. The order is:
Notice that we were passing through the graph not drawing the graph. We don't have to show every edges in the graph.
Code:
See as much as one node can!
For example, we start from node a.
Next, check all the connected edges from a. Node c will be encountered first. Instead of moving to node c, we save it in queue and still stay at node a.
Visit node d and save it into queue.
The nodes connected to a had already been visited. Pop out c from queue.
Continue visiting other nodes connect to c.
Finish node c. Pop out d
Finish node d. Pop out b.
Finish node b. Also, queue is empty. Stop program. The order is:
Code:
So far, we have introduced the basic concept of graph. We introduced the types of graph, how can we express the graph using different structures and how to pass through the graph. In next article, we're going to discuss how can we find the shortest path.