Graphs — adjacency lists and BFS
Modeling graphs in plain Java with Map<Node, List<Node>>, then walking them breadth-first.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
Two representations
An adjacency list — Map<Node, List<Node>> — is compact and easy to traverse when edges are sparse. An adjacency matrix — boolean[n][n] — is dense but gives O(1) edge lookup and is best when the graph is small or nearly complete. For most application-level graphs (social networks, dependency graphs, tile maps), the adjacency list wins.
Directed, undirected, weighted
In a directed graph, add A→B by putting B in A's neighbor list only. In an undirected graph, add both directions. For weighted edges, replace the neighbor list with a list of record Edge(Node to, double weight) {}. Java has no built-in graph class, but a Map<Node, List<Edge>> is a clean, honest model.
BFS: shortest paths in unweighted graphs
Breadth-first search visits nodes in order of hop distance from the source. Use a queue plus a Set<Node> visited. Set.add returning true doubles as the visited check — a very tidy Java idiom. BFS finds the shortest number of hops to every reachable node.
DFS: recursion or explicit stack
Depth-first search goes as deep as possible before backtracking. Recursive DFS is the easiest to write; for very deep graphs, use an explicit Deque<Node> as a stack to avoid StackOverflowError. DFS is the right tool for cycle detection, topological sort, and finding connected components.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
Dijkstra for weighted shortest paths
Replace BFS's queue with a PriorityQueue keyed by tentative distance. Poll the closest unvisited node, relax its edges, repeat. Runs in O((V+E) log V) with a binary heap and handles any non-negative edge weights. For negative weights you need Bellman-Ford.
Real-world graph libraries
For non-trivial graph work, reach for JGraphT or Guava's com.google.common.graph. Both give you edge/vertex objects, algorithms (Dijkstra, Kruskal, Kosaraju), and immutable builders. Learn the plain-Java version first — it makes the library APIs obvious.