Graphs Representation, BFS, DFS
Graph representations Nodes or vertices Edges Weighted vs. unweighted Undirected vs. directed Multiple edges or not Self-loops or not
Degree Vertex degree: edges for that vertex Undirected Directed Degree is the number of edges leaving vertex Self loops count twice Number of edges = 2*sum of vertex degrees Directed In-degree (incoming edge count) and out-degree (outgoing edge count) Sum of all in-degrees equals sum of all out-degrees
Traveling a graph Path/walk/trail Cycle/circuit/tour Follow edges along vertices Could repeat edge unless stated otherwise Cycle/circuit/tour Path that leads back to the original vertex Usually assumes won’t follow same edge, but not always
Storing graphs Edge list Keep a list of all edges Store start, end, weight Good if you need to work with all the edges at once Kruskal’s MST algorithm Not good at all if you want to know the adjacent edges for any one vertex
Storing graphs Adjacency list Keep a list of edges in each vertex Can be used for directed or undirected Undirected – must keep consistent on both ends Can keep weights per edge in the node list Or, store pointer to a light edge structure Good to find and iterate through edges for any vertex Typical “default” implementation for a graph
Storing graphs Adjacency matrix Store matrix indicating edges between vertices (rows/columns) Directed: rows are from, columns are to Value in the cell can be the weight of the edge Bad if the graph is sparse, or too large Can sometimes phrase graph calculations as matrix calculations this way; then, it can be more efficient to compute with
Depth-First Search Keep global list of visited T/F (or a number indicating which “tree” it is part of) Recursive function: Mark current node visited For all adjacent edges: If the node is unvisited, visit it Basically, keep a stack of nodes that you want to visit Forms the basis for several other operations
Breadth-first search Keep a “distance” for each node, initialized to infinity Keep queue of nodes to process, start with intro node Repeatedly pop a node off the queue Go through list of adjacent nodes If node is infinity away, then set its distance to current distance plus one and add to queue Has a few good uses Shortest path in an undirected graph