BFS

    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        if (rooms == null || rooms.size() == 0) {
            return true;
        }
        Set<Integer> visited = new HashSet<>();
        Queue<Integer> q = new LinkedList<>();
        q.offer(0);
        visited.add(0);
        while (!q.isEmpty()) {
            int curt = q.poll();
            for (int next : rooms.get(curt)) {
                if (!visited.contains(next)) {
                    q.offer(next);
                    visited.add(next);
                }
            }
        }
        return visited.size() == rooms.size();
    }

Count the number of oranges and rotten oranges. Starting with all rotten oranges in the queue, traverse in level order to fill all good oranges. Return the number of levels if the all oranges are rotten (check count).

Given a 2D boolean array where true represents water and false represents land, generate a grid with highest possible peak. Rules are:

  1. the height of any water cell is 0.

  2. the height of any land cell cannot differ for more than one from any of the neighboring (sharing one edge) cells.

Add all "T" nodes into a BFS queue and trigger a BFS from all those nodes. Also, maintain the distance used to reach each node alongside. Once the BFS visits all the nodes, return the distance to reach every node as the answer.

For the followup:- From all the nodes that have reached max peak height, trigger another BFS that goes from max peak height node to other nodes decrementing the distance. This would lead to more nodes having a height of 0

Build graph by using stop to next available stops. Level order BFS to find the next stops, return step/level when reach stop T. (This answer will return TLE when there are too many stops)

One modification is to check duplicate on bus route, instead of bus stops. That will eliminate lots of path since all stops on traveled path are redundant.

N is number of stops, T is the stops * edges: T: O(n^2)

Find the next node by extending the directions, until reach boundary or wall. Use boolean[][] visited to record all visited nodes.

The BFS solution requires to store all path to destination. Use a dist matrix to store the minimum distance between each grid and start point. Replace the distance when new calculated steps is less than the earlier calculations. Output result as all distances are calculated.

Solution: Dijkstra

Given a knight in a chessboard (a binary matrix with 0as empty a 1as barrier) with a source position, find the shortest path to a destination position, return the length of the route.

Return -1 if knight can not reached.

Notice

  • Source and destination must be empty.

  • Knight can not enter the barrier.

Fill the result matrix with Integer.MAX_VALUE to detect if the node has been visited. Starting from 0 grids, use BFS to detect if the next distance from 0 is larger than expected, if so, correct it to the right value. Offer that next node to the queue.

T: O(m * n) S: O(m * n)

T: O(k^2 * N) N is number of words and k is the average length of words

Use BFS level order traversal to build graph and record distance from start node. DFS to build path.

Use a map to store the relationship key: current node value: corresponding new node. Traverse the graph with a curt node and add corresponding neighbors to the neighbors list.

T: O(n)

DFS link

Convert index to board by using:

  • int row = n - (next - 1) / n - 1

  • int col = (n - row) % 2 != 0 ? (next - 1) % n : n - (next - 1) % n - 1

Similar as 127. Word Ladder.

Check on curt get TLE, however check both on curt and next should work.

bfs level order traverse starts from all buildings, go through all each empty grids, to calculate the cumulated shortest distance from all buildings. Also count how many houses can reach this spot, when output, detect if this spot can be reached by all starting points.

T: O((mn)^2) .S: O(mn)

BFS Level order traversal.

2096. Step-By-Step Directions From a Binary Tree Node to Another

2603. Collect Coins in a Tree

Approach

  1. Prune all useless leaf nodes recursively:

    • Start by removing leaf nodes that do not contain coins.

    • When you remove a leaf, its parent might become a leaf.

    • If that new leaf also has no coin, remove it as well.

    • Repeat this process until all remaining leaves have coins.

  2. Simulate collecting coins from grandparent nodes:

    • Once only coin-containing leaves remain, we assume the coins can be collected from 2 hops away.

    • So, we remove the leaves and their direct parents, since we don’t need to walk all the way to the leaves.

  3. Count remaining edges:

    • After the pruning steps, count the remaining edges.

    • Since we count both directions (a → b and b → a), we multiply the remaining edge count by 2.


Complexity

  • Time Complexity: O(n) — each node and edge is processed at most a few times.

  • Space Complexity: O(n) — for adjacency lists, degree counts, and queues.

Last updated

Was this helpful?