Practice: graph traversal
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Applying graph traversals to boundary problems, shape hashing, and graph deep copying solidifies traversal skills.
Boundary-connected traversals: Surrounded regions and enclaves
Many grid graph problems ask to identify regions that cannot reach the grid boundary. In Surrounded Regions, 'O' cells completely surrounded by 'X' must be flipped to 'X'. Any 'O' connected to the outer boundary cannot be captured.
Example 1 · Surrounded Regions via Boundary DFS
public class Main { static void solve(char[][] board) { if (board == null || board.length == 0) return; int rows = board.length, cols = board[0].length;
// Traverse boundary cells for (int r = 0; r < rows; r++) { if (board[r][0] == 'O') dfs(board, r, 0, rows, cols); if (board[r][cols - 1] == 'O') dfs(board, r, cols - 1, rows, cols); } for (int c = 0; c < cols; c++) { if (board[0][c] == 'O') dfs(board, 0, c, rows, cols); if (board[rows - 1][c] == 'O') dfs(board, rows - 1, c, rows, cols); }
// Flip surrounded to 'X' and restore boundary connected 'S' to 'O' for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (board[r][c] == 'O') board[r][c] = 'X'; else if (board[r][c] == 'S') board[r][c] = 'O'; } } }
static void dfs(char[][] board, int r, int c, int rows, int cols) { if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != 'O') return; board[r][c] = 'S'; // Safe marker dfs(board, r - 1, c, rows, cols); dfs(board, r + 1, c, rows, cols); dfs(board, r, c - 1, rows, cols); dfs(board, r, c + 1, rows, cols); }
public static void main(String[] args) { char[][] board = { {'X', 'X', 'X', 'X'}, {'X', 'O', 'O', 'X'}, {'X', 'X', 'O', 'X'}, {'X', 'O', 'X', 'X'} }; solve(board); for (char[] row : board) System.out.println(new String(row)); }}XXXX XXXX XXXX XOXX
What this code does
- Interior 'O' cells at (1,1), (1,2), and (2,2) do not touch boundaries and become 'X'.
- Boundary 'O' at (3,1) is marked safe 'S' and restored back to 'O'.
- Total grid is updated in O(R * C) time using boundary-first search.
Example 2 · Number of Enclaves in a Binary Grid
public class Main { static int numEnclaves(int[][] grid) { int rows = grid.length, cols = grid[0].length;
// Flood fill from boundary 1s for (int r = 0; r < rows; r++) { if (grid[r][0] == 1) dfs(grid, r, 0, rows, cols); if (grid[r][cols - 1] == 1) dfs(grid, r, cols - 1, rows, cols); } for (int c = 0; c < cols; c++) { if (grid[0][c] == 1) dfs(grid, 0, c, rows, cols); if (grid[rows - 1][c] == 1) dfs(grid, rows - 1, c, rows, cols); }
// Count remaining interior 1s int enclaves = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (grid[r][c] == 1) enclaves++; } } return enclaves; }
static void dfs(int[][] grid, int r, int c, int rows, int cols) { if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != 1) return; grid[r][c] = 0; dfs(grid, r - 1, c, rows, cols); dfs(grid, r + 1, c, rows, cols); dfs(grid, r, c - 1, rows, cols); dfs(grid, r, c + 1, rows, cols); }
public static void main(String[] args) { int[][] grid = { {0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0} }; System.out.println("Enclaves count: " + numEnclaves(grid)); }}Enclaves count: 3
What this code does
- Cell at (1,0) touches the left boundary and is drained to 0.
- Interior cluster {(1,2), (2,1), (2,2)} cannot reach any boundary.
- Returns 3 as the total count of trapped enclave cells.
Instead of searching inward from every internal cell, invert the search perspective. Start traversals exclusively from all 'O' cells located along the four outer boundaries. Traverse all connected 'O' cells using DFS or BFS and temporarily mark them as safe. After boundary traversals conclude, iterate through the entire matrix. Convert unvisited 'O' cells to 'X' because they are fully surrounded. Restore safe temporary cells back to 'O'. Number of Enclaves uses this exact boundary-first traversal technique in O(R * C) time.
Deep copying graphs with HashMap vertex mappings
A deep copy duplicates every node and every connection, so changing the copy never changes the original graph.
Cloning a graph requires making a deep copy where all nodes and edge connections are duplicated. A simple traversal that creates new nodes naively can clone the same vertex multiple times. Cycles in the graph cause infinite recursion and out-of-memory errors.
Example 3 · Cloning a Graph with a Map
import java.util.*;
public class Main { static class Node { int val; List<Node> neighbors; Node(int val) { this.val = val; this.neighbors = new ArrayList<>(); } }
static Node cloneGraph(Node node, Map<Node, Node> map) { if (node == null) return null; if (map.containsKey(node)) return map.get(node);
Node copy = new Node(node.val); map.put(node, copy);
for (Node neighbor : node.neighbors) { copy.neighbors.add(cloneGraph(neighbor, map)); } return copy; }
public static void main(String[] args) { Node n1 = new Node(1); Node n2 = new Node(2); n1.neighbors.add(n2); n2.neighbors.add(n1);
Map<Node, Node> map = new HashMap<>(); Node clone = cloneGraph(n1, map);
System.out.println("Cloned root val: " + clone.val); System.out.println("Cloned distinct object: " + (clone != n1)); System.out.println("Cloned neighbor val: " + clone.neighbors.get(0).val); }}Cloned root val: 1 Cloned distinct object: true Cloned neighbor val: 2
What this code does
- Map tracks original node references mapped to newly instantiated clone nodes.
- Cycles in the graph return cached clone nodes from map without infinite recursion.
- Verifies new nodes are distinct memory objects with identical values and edges.
To prevent duplicates and cycles, maintain a HashMap mapping each original node to its new copy. When visiting node u, check if map contains u. If not, instantiate Node copy = new Node(u.val) and insert map.put(u, copy). Then iterate over all neighbours of u. Recursively clone each neighbour and add the cloned neighbour to copy.neighbours list. This clones any graph structure with arbitrary cycles in linear O(V + E) time.
Shape hashing for distinct islands and picking BFS versus DFS
The Number of Distinct Islands problem counts island shapes that differ even after sliding. Record each island's cells relative to its first cell and store that signature in a HashSet.
// Collect one island's cells relative to its first cell (r0, c0)void dfs(int[][] grid, int r, int c, int r0, int c0, StringBuilder shape) { if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] != 1) return; grid[r][c] = 0; // mark visited shape.append(r - r0).append(',').append(c - c0).append(';'); // relative position dfs(grid, r + 1, c, r0, c0, shape); dfs(grid, r - 1, c, r0, c0, shape); dfs(grid, r, c + 1, r0, c0, shape); dfs(grid, r, c - 1, r0, c0, shape);}// shapes.add(shape.toString()); the set's size = number of distinct islandsSubtract the starting cell (r0, c0) from each cell, giving (r - r0, c - c0), or record the sequence of move letters ('U', 'D', 'L', 'R', 'B'). The size of the set is the number of distinct shapes.
Choose BFS for shortest paths or minimum steps in an unweighted graph. Choose DFS for building paths, boundary flooding, topological sorting and cycle detection.
Finish up
Mark complete & continue
Next: Shortest path with BFS