(7) Graphs Flashcards
1
Q
Definition Graphs
A
- Graphs allow to represent pairs of elements and a relationship between these elements
- A graph is a pair of a set of vertices V (nodes) and a set of edges E (pairs)
2
Q
How is a graph implemented?
A
- Store all vertices: Create a class Vertex and store for each vertex one object in a VertexNode in a List
- Store all edges: - Option 1: Create a class Edge with two attributes of the type Vertex, create an edge object for each edge in the graph and store all Edge objets in EdgeNodes in a List
- Option 2: create a list of neighbours in each vertex object, and store all neighbours in this list
3
Q
Which classes do we need for a graph?
A
- Vertex class: stores some data and a List of VertexNodes with all neighbours
- VertexNode class: stores a reference to a Vertex and a reference to the next VertexNode
- List class: stores a reference to the first VertexNode
- Graph class: stores a List of all the VertexNodes
4
Q
What kinds of graphs exist?
A
- directed: (v1, v2) does not imply (v2, v1) - undirected graphs (v1, v2) if and only if (v2, v1)
5
Q
Weighted Graph Definition
A
- weighted graphs have weights attached to each edge (can be directed or undirected)
- in an unweighted graph all edges have same weight
6
Q
What are use cases for graphs?
A
- Subway networks
- Supply-chains
7
Q
Which methods exist to search in a graph?
A
- Breadth first search (horizontal first)
- Dealt first search (go as deep as possible)
8
Q
What is the procedure of the breadth-first search algorithm?
A
- start at a given node (=current_node)
- if current_node = e -> we are done
- if current_node ≠ e:
- mark current_node as visited
- enqueue all unmarked nodes which are direct neighbour nodes to current_node in queue nodes_to_visit
– mark them as added nodes - if nodes_to_visit is empty -> we are done, element was not found
- dequeue element from queue nodes_to_visit and set it as current_node
- go to step 2
9
Q
What is the time complexity of the breadth-first search algorithm?
A
- O(E + V)
- Worst Case: all nodes are connected with each other
10
Q
Which algorithm can be used to find the shortest path?
A
Dijkstra algorithm
11
Q
What is the procedure of the Dijkstra algorithm?
A
- Initialize the starting node with “0” and all other nodes with ∞
- Repeat the following steps until all nodes are visited (Dijkstra):
1. Choose an unvisited node with the shortest distance to the initial node and set it as current_node
2. Check for every unvisited neighbour node of current_node: Is the path via current_node to the neighbour node shorter than the tentative distance to the neighbour node (value in the node)? update distance value
4. Mark current_node as visited
12
Q
What is the Dijkstra algorithm used for?
A
- Find the shortest path from a source node to every other node in the graph
13
Q
What is the time complexity of the Dijkstra algorithm?
A
- O(V^2 + E) = O(V^2)