Intermediate·Concept·2 min read

Graphs in Java

Practice this question

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);
        }
    }
}

Adapted from 15_DSA_JAVA.md · “9. Graphs in Java”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.