Code Logo

Disaster Relief Route Tracker

Published atDate not available
Medium 0 views
Like0

This problem feels like a little puzzle you can solve one step at a time. In Disaster Relief Route Tracker, you are trying to work toward the right number by following one clear idea.

Here, you are mostly deciding whether a rule stays true while you look through the input. Sometimes that means checking if things are connected, balanced, or allowed. Sometimes it means noticing the first place where the rule breaks. The answer depends on being careful from beginning to end.

For example, if the input is n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[1,5]], start = 1, blocked_shelters = [4], the answer is 5. The convoy reaches shelters 1, 0, 2, 3, and 5 while skipping the blocked shelter 4. Another example is n = 4, roads = [], start = 2, blocked_shelters = [], which gives 1. With no roads, only the staging shelter receives supplies.

This problem needs a little more patience than a very easy one. The key is noticing the exact moment when the rule stays true or breaks.

Example Input & Output

Example 1
Input
n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[1,5]], start = 1, blocked_shelters = [4]
Output
5
Explanation

The convoy reaches shelters 1, 0, 2, 3, and 5 while skipping the blocked shelter 4.

Example 2
Input
n = 4, roads = [], start = 2, blocked_shelters = []
Output
1
Explanation

With no roads, only the staging shelter receives supplies.

Example 3
Input
n = 5, roads = [[0,1],[1,2],[2,3],[3,4]], start = 0, blocked_shelters = [2]
Output
2
Explanation

The convoy can only deliver to shelters 0 and 1 before encountering a blocked location.

Algorithm Flow

Recommendation Algorithm Flow for Disaster Relief Route Tracker
Recommendation Algorithm Flow for Disaster Relief Route Tracker

Best Answers

java
import java.util.*;

class Solution {
    public int disaster_relief_route_tracker(int n, int[][] roads, int start, int[] blocked_shelters) {
        Set<Integer> blocked = new HashSet<>();
        for (int s : blocked_shelters) blocked.add(s);
        if (blocked.contains(start)) return 0;
        List<Integer>[] adj = new ArrayList[n];
        for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
        for (int[] road : roads) {
            adj[road[0]].add(road[1]);
            adj[road[1]].add(road[0]);
        }
        Set<Integer> visited = new HashSet<>();
        Queue<Integer> queue = new LinkedList<>();
        visited.add(start);
        queue.add(start);
        while (!queue.isEmpty()) {
            int u = queue.poll();
            for (int v : adj[u]) {
                if (!visited.contains(v) && !blocked.contains(v)) {
                    visited.add(v);
                    queue.add(v);
                }
            }
        }
        return visited.size();
    }
}