LESSON 42 / 75·2 min readIntermediate

Graphs in Java

Should knowConcept lesson
01 Understand02 Recall03 Prepare

Graph representation

  • adjacency list using List<List<Integer>>
  • adjacency matrix for dense graphs

Problems to practice

  • Number of Islands
  • Clone Graph
  • Course Schedule
  • Topological Sort
  • DFS/BFS traversal
  • Shortest Path (BFS / Dijkstra)
  • Union-Find problems

BFS example

java
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.offer(start);
visited.add(start);

while (!queue.isEmpty()) {
    int node = queue.poll();
    for (int next : graph.get(node)) {
        if (!visited.contains(next)) {
            visited.add(next);
            queue.offer(next);
        }
    }
}

PAUSE & RECALL

Can you explain it without the notes?

Graphs in Java

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

Graph representation

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: Dynamic programming in Java

Adapted from 15_DSA_JAVA.md · “9. Graphs in Java”. Examples are study fragments; framework behavior can depend on your version.