DFS Topological Sort and Shorstest Path Problem Flashcards
Topological Sort
- Topological sort
- DFS can be used to perform a topological sort of a directed acyclic graph
- A topological sort of a DAG is a linear ordering of all its vertices such that if DAG contains an edge (u, v), then u appears before v in ordering
Topological Sort Wotk
• Don’t need to sort by finish times
– Can just output vertices as they are finished and understand that we want the reverse of this list
Shortest path problem examples
- Airlineflighttimes
- Telephonecommunicationcosts
- Computernetworksresponsetimes • Fastestwaytogettoschoolbycar
Single-source shortest path
Find a shortest path from a given source (vertex s) to each of the vertices. Dijkstra’s algorithm.
Single-pair shortest path
Given two vertices, find a shortest path between them.
All-pairs shortest path
Find shortest-paths for every pair of vertices.
Shortest path problem definition #1
• Definition 1: Given a path p=v1 →v2 →…→vk , the weight of the path is the sum of the weights of all its edges
Shortest path problem definition #2
• Definition 2: The shortest path weight from u to v is defined
by:
δ(u,v)=% {()$min w p : p path from u to v if there is a path from u to v
∞ otherwise
Shortest path problem definition #3
A shortest path from vertex u to vertex v is defined as any path p with weight w(p)= δ(u,v)
Dijkstra’s algorithm
Assumptions:
– Directed or undirected graph
– All edges must have nonnegative weights
– Connected graph
• Input: Weighted graph G=(E,V) and source vertex v∈V
•Output: Lengths of shortest paths from a given source
vertex v ∈ V to all other vertices
–
With slight modification we can obtain the path
Dijkstra’s algorithm running time
|V|Time-extract-min + |E|Time-Decrease-key
Greedy Algorithm
•Dijkstra’s algorithm uses a greedy strategy for designing algorithms
• Greedy approach
– In order to get what you want just start grabbing what looks best
- Shortest path we wish to find the path with lowest weight
- It always chooses the lightest vertex
Topological Sort Algorithm
TOPOLOGICAL-SORT(G)
call DFS(G) to compute finishing time for each vertex v
as each vertex is finished, insert it onto the front of a linked list
return linked list
Can just output vertices as they are finished and understand that we want the reverse of this list
• Space:O(V+E) • Time:O(V+E)