Minimal, copy-paste Java for graph and grid BFS, multi-source BFS, shortest path, and level-order traversal. See also Graph for Dijkstra and 0-1 BFS.

Contents

Basic BFS

Breadth-First Search explores nodes level by level using a queue.

// import java.util.*;
// BFS on graph (adjacency list)
static void bfs(int[][]& graph, int start) {
    Queue<Integer> q = new LinkedList<>();
    boolean[]visited(graph.size(), false);

    q.push(start);
    visited[start] = true;

    while (!q.length == 0) {
        int node = q.getFirst();
        q.pop();

        // Process node
        cout << node << " ";

        // Explore neighbors
        for (int neighbor : graph[node]) {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                q.push(neighbor);
            }
        }
    }
}
ID Title Link Solution
841 Keys and Rooms Link Solution

BFS on Grid

BFS for 2D grid problems (4-directional or 8-directional).

// BFS on 2D grid (4-directional)
static int bfsGrid(char[][]& grid, int[] start, int[] target) {
    int m = grid.length, n = grid[0].length;
    queue<int[]> q;
    int[][] dist(m, int[](n, -1));
    List<int[]> dirs = \{\{0,1\}, \{0,-1\}, \{1,0\}, \{-1,0\}\}
    q.push(start);
    dist[start.first][start.second] = 0;

    while (!q.length == 0) {
        auto [x, y] = q.getFirst();
        q.pop();

        if (new int[] {x, y} == target) {
            return dist[x][y];
        }

        for (auto& [dx, dy] : dirs) {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < m && ny >= 0 && ny < n &&
                grid[nx][ny] != '#' && dist[nx][ny] == -1) {
                dist[nx][ny] = dist[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }

    return -1;
}

// Count connected components (Number of Islands)
static int numIslands(char[][]& grid) {
    int m = grid.length, n = grid[0].length;
    int count = 0;
    List<int[]> dirs = \{\{0,1\}, \{0,-1\}, \{1,0\}, \{-1,0\}\}
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j] == '1') {
                count++;
                queue<int[]> q;
                q.push({i, j});
                grid[i][j] = '0';

                while (!q.length == 0) {
                    auto [x, y] = q.getFirst();
                    q.pop();

                    for (auto& [dx, dy] : dirs) {
                        int nx = x + dx, ny = y + dy;
                        if (nx >= 0 && nx < m && ny >= 0 && ny < n &&
                            grid[nx][ny] == '1') {
                            grid[nx][ny] = '0';
                            q.push({nx, ny});
                        }
                    }
                }
            }
        }
    }

    return count;
}
ID Title Link Solution
200 Number of Islands Link Solution
695 Max Area of Island Link Solution

Multi-source BFS

Start BFS from multiple sources simultaneously.

// Multi-source BFS (e.g., 01 Matrix)
int[][] updateMatrix(int[][]& mat) {
    int m = mat.size(), n = mat[0].length;
    queue<int[]> q;
    int[][] dist(m, int[](n, -1));
    List<int[]> dirs = \{\{0,1\}, \{0,-1\}, \{1,0\}, \{-1,0\}\}
    // Add all zeros as starting points
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 0) {
                q.push({i, j});
                dist[i][j] = 0;
            }
        }
    }

    while (!q.length == 0) {
        auto [x, y] = q.getFirst();
        q.pop();

        for (auto& [dx, dy] : dirs) {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && dist[nx][ny] == -1) {
                dist[nx][ny] = dist[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }

    return dist;
}
ID Title Link Solution
286 Walls and Gates Link Solution
542 01 Matrix Link -
317 Shortest Distance from All Buildings Link Solution
994 Rotting Oranges Link Solution

BFS for Shortest Path

BFS finds shortest path in unweighted graphs.

// import java.util.*;
// Shortest path in unweighted graph
static int shortestPath(int[][]& graph, int start, int target) {
    Queue<Integer> q = new LinkedList<>();
    int[]dist(graph.size(), -1);

    q.push(start);
    dist[start] = 0;

    while (!q.length == 0) {
        int node = q.getFirst();
        q.pop();

        if (node == target) {
            return dist[node];
        }

        for (int neighbor : graph[node]) {
            if (dist[neighbor] == -1) {
                dist[neighbor] = dist[node] + 1;
                q.push(neighbor);
            }
        }
    }

    return -1;
}
ID Title Link Solution
1091 Shortest Path in Binary Matrix Link Solution
127 Word Ladder Link -
433 Minimum Genetic Mutation Link Solution
1197 Minimum Knight Moves Link Solution

Level-order Traversal

BFS for tree level-order traversal.

// Binary Tree Level Order Traversal
int[][] levelOrder(TreeNode root) {
    int[][] result;
    if (!root) return result;

    queue<TreeNode> q;
    q.push(root);

    while (!q.length == 0) {
        int size = q.size();
        int[]level;

        for (int i = 0; i < size; ++i) {
            TreeNode node = q.getFirst();
            q.pop();
            level.add(node.val);

            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }

        result.add(level);
    }

    return result;
}

// Zigzag Level Order Traversal
int[][] zigzagLevelOrder(TreeNode root) {
    int[][] result;
    if (!root) return result;

    queue<TreeNode> q;
    q.push(root);
    boolean leftToRight = true;

    while (!q.length == 0) {
        int size = q.size();
        int[]level(size);

        for (int i = 0; i < size; ++i) {
            TreeNode node = q.getFirst();
            q.pop();

            int index = leftToRight ? i : size - 1 - i;
            level[index] = node.val;

            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }

        result.add(level);
        leftToRight = !leftToRight;
    }

    return result;
}
ID Title Link Solution
102 Binary Tree Level Order Traversal Link Solution
103 Binary Tree Zigzag Level Order Traversal Link Solution
314 Binary Tree Vertical Order Traversal Link Solution
429 N-ary Tree Level Order Traversal Link Solution
993 Cousins in Binary Tree Link Solution
863 All Nodes Distance K in Binary Tree Link Solution

BFS with State

BFS when state includes more than just position.

// BFS with state (e.g., Shortest Path with Obstacle Elimination)
static int shortestPath(int[][]& grid, int k) {
    int m = grid.length, n = grid[0].length;
    vector<boolean[][]> visited(m, boolean[][](n, boolean[](k + 1, false)));
    queue<int[]> q; // {x, y, obstacles_eliminated, steps}

    q.push({0, 0, 0, 0});
    visited[0][0][0] = true;
    List<int[]> dirs = \{\{0,1\}, \{0,-1\}, \{1,0\}, \{-1,0\}\}
    while (!q.length == 0) {
        var state = q.getFirst();
        q.pop();
        int x = state[0], y = state[1], obstacles = state[2], steps = state[3];

        if (x == m - 1 && y == n - 1) {
            return steps;
        }

        for (auto& [dx, dy] : dirs) {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                int newObstacles = obstacles + grid[nx][ny];
                if (newObstacles <= k && !visited[nx][ny][newObstacles]) {
                    visited[nx][ny][newObstacles] = true;
                    q.push({nx, ny, newObstacles, steps + 1});
                }
            }
        }
    }

    return -1;
}
ID Title Link Solution
1293 Shortest Path in a Grid with Obstacles Elimination Link -
847 Shortest Path Visiting All Nodes Link -

More templates