Week 8 Flashcards
Implementations to store Graphs
Advancency List. Each node mapped to a List of adjacent nodes
Edge Set: each node mapped to a set of Edges containing source, destination and weight of edge
Graph Travesal Patterns
Breadth First
Depth First
Breadth First
Start with source node
Visist all its neighbors
Then visit all their neihbors
etc. until target node found
What does Breadth first algorithm guarantees
That we find always shortest path
Depth First
Start at source node
visit one of its neigbors
then visit one of its neighbor
If node has no neighbors, or all already visited, go back to previous node and visit the next neighbor not visited
private boolean doDfs(String start, String elementToFind) { if (start.equals(elementToFind)) { return true; } else { marked.add(start); for (String neighbor : getNodeNeighbors(start)) { if (!marked.contains(neighbor) && doDfs(neighbor, elementToFind)) return true; } return false; } }
How many times is an edge examined in DFS
At most twice for undirected, and at most once for directed
Time Complexity of BFS and DFS
Both O (V + E)
V = # vertices
E = # Edgeds
BFS vs DFS which more efficient
Space wise DFS as it only needs to maintained data structure for marked. BFS additionally needs to maintain one for toExplore
When use DFS
Find directed cycle or identifying SCC
Is a cycle C in a graph a valid path?
A path is defined as a list of nodes from a start node to an end node in which each successive pair of nodes is connected by an edge. The start and end nodes being the same does not violate the definition of a path.
Min number of edges for G to be connected
n-1
Given an undirected/directed graph G with n nodes, what is the maximum number of edges possible for G if no nodes have self-loops (edges that connect a node to itself)?
n(n-1)/2 = undirected
n(n-1) = directed