Chapter 38: Graphs and Chapter 63: Graph Traversal Algorithms Flashcards
What is a graph
A graph is a set of vertices/nodes connected by edges/arcs.
Undirected graph
All edges are bidirectional
Directed graph
The edges are unidirectional
Advantages compared to Linked List/Binary Tree
Each vertex can have more than 2 edges therefore able to point to any vertex in the data structure
Weighted graph
Where each edge is given an value to show the cost of going from one vertex to another.
Adjacency list (define)
Adjacency lists: storing graphs as objects or using a dictionary.
Adjacency list (python syntax with/without weights)
Python syntax (no weights): graph = {“A”:[“B”,”D”,”E”,”F”]…}
Python syntac (with weights): graph = {“A”:[“B”:57,”D”:56,”E”:45,”F”:25]…}
Adjacency Matrix
Adjacency matrix: a 2d array which stores the value of the weight of the edge between 2 vertices.
Symmetrical with an undirected graph (with 0 top left to bottom right).
Pros: very convenient (adding an edge is simple).
Cons: A sparse graph with many nodes but not many edges will lead to lots of 0s/empty cells therefore inefficient
Uses of graphs in computer science
- Mapping road networks for navigation systems
- Storing social network data
- Resource allocation in operating systems
- Representing molecular structures and geometry.
Types of graph traversals
There are 2 ways of traversing a graph:
- A depth-first traversal
- A breadth-first traversal
Depth-first traversal
In this traversal, we go as far down one route as we can before backtracking and taking the next route.
- Uses an edge-based technique
- Makes use of the stack data structure
Depth-first traversal algorithm
- Set the root node as the current node
- Add the current node to the list of visited nodes (if it isn’t already in the list)
- Go through all the connected nodes to the current node
- (i) If the current node isn’t in visited nodes, push it onto the stack. Usually traverse on the left side of the graph - Pop the node from the stack and set it to current node
- Start again through step 2.
Once we get to the end of one route, there will be no further nodes to push onto the stack therefore it will pop the next node which is the start of the next route.