Graphs Flashcards
What is a graph?
A set of vertices and edges. Each edge connects a pair of verticies
What is a path in a graph
A sequences of vertices connected by edges with no repeated edges
What is a simple path in a graph?
A path (which is a sequence of vertices connected by edges, with no repeated edges) with no repeated vertices.
What is a cycle in a graph?
A path (which is a sequence of vertices connected by edges, where no edge is repeated) with at least one edge. The path’s first and last vertices are the same.
What is a simple cycle?
A cycle (which is a path with at least one edge whose first and last vertices are the same, and where a path is a sequence of vertices connected by edges with no repeated edges) with no repeated vertices. Note that the first and last vertices will be the same.
What is the length of a cycle or path in a graph?
It is the number of edges in a path (vertices connected by edges with no repeated vertices) or a cycle (path with at least one edge whose first and last vertices are the same).
What is a connected graph?
A graph that contains a path (vertices with no rotated edges) between all vertices.
Describe a tree in terms of a graph
An acyclic connected graph (or a graph with no cycles and where every vertex has a path to every other vertex)
What is a spanning tree of a connected graph?
A connected graph is a graph that contains a path from every vertex, to every other vertex. The spanning tree is a subgraph that contains all the vertices of the connected graph. The subgraph is a tree (acyclic and connected graph)
Describe how a depth first search algorithm visits the vertices of a graph
When visiting a vertex
- Mark it as visited
- Visit (recursively) all the vertices that are adjacent to it and that have not yet been marked
What is the time complexity of DFS when marking all nodes?
The time complexity is proportional to the sum of all vertices degrees.
Write a simple DFS algorithm that searches each vertex.
private void dfs(int source) {
marked[source] = true;
count++;
for(int w : adj.get(source))
if (!marked[w]) dfs(w)
Name two problems DFS can solve when looking at graphs
Connectivity: are two different vertices connected? How many connected components does a graph have?
Single-source paths: find a path from source vertex to target vertex
Write a simple DFS algorithm that finds paths from a source to all vertices
Utilize an array called edgeTo[], where edgeTo[w] = v indicates that v-w edge accesses w first in the path. The array is a parent-link representation of the tree rooted at the source. Said another way v is the parent of w.
Private void dfs(int s) {
marked[v] = true;
for (int w : adj.get(s)) {
if (!marked[w]) {
edgeTo[w] = s;
dfs(w);
}
}
}
What is the time complexity of a depth first search algorithm providing a path from a source vertex to a target vertex?
The time complexity is equal to the length of the path.