1/8
Looks like no tags are added yet.
What is a graph?
A non-linear data structure consisting of edges and vertices where each vertex/node holds data. Edges can be one-way (directed) or two-way (undirected) as well as have weights.
What is an adjacency list?
A way to represent a graph using a collection of lists where each vertex stores a list of all the other nodes it directly connects to with edges.
A HashMap acts like a fast lookup table where each key is a node or vertex in the graph
Each node/vertex points to a List data structure that contains the edge information
Sparse vs Dense Graphs: V vertices and E edges
Sparse: the # of edges is relatively low compared to the # of nodes (typical edge count is O(V) or O(V log V))
Dense: the typical edge count is close to O(V²)
What are some advantages of Sparse Graphs?
Fewer Edges: more memory efficient; less storage needed
Faster Processing: graph algorithms perform faster because they process fewer edges
How does Depth-First Search work?
Start at the root: mark as visited and push onto the stack
Explore an unvisited neighbor: move to an adjacent unvisited node, mark as visited, push it onto the stack
Continue exploring until you reach a node with no unvisited neighbors: pop it off the stack to return to the previous node
Repeat: continue checking for unvisited neighbors and backtracking until the stack is completely empty
Adjacency List vs Adjacency Matrix
Use an Adjacency List when the graph is sparse—less edges compared to nodes.
List<Integer>[] or ArrayList<ArrayList<Integer>>
Map<Node, List<Node> or HashMap<Node, ArrayList<Node>>
Use an Adjacency Matrix when the graph is dense—more edges compared to nodes.
A 2D Array: int [][] matrix or double [][] matrix … something similar
Explain how a sparse graph uses a List data structure
There are Two Levels:
Finding a Node: Lookup table (HashMap or ArrayList) that stores a reference to each node’s connection List
Reading its Connections: Small, inner dynamic List (ArrayList) containing only its actual connected neighbors
How does Breadth-First Search work?
Explores a graph layer by layer, visiting all of a node’s immediate neighbors before moving on to their neighbors.
Start at the root node: mark it as visited and add it to the back of the queue
Dequeue the front node: pull the oldest node from the front of the queue (queue.poll())
Explore all immediate neighbors: look up that node’s ArrayList of neighbors
Enqueue unvisited neighbors: for every neighbor that hasn’t been visited yet, mark it as visited immediately and add it to the back of the queue (queue.offer())
Repeat: keep pulling from the front of the queue until its completely empty