1. Per-Query Breadth-First Search (BFS)
Intuition
For every query [p, q, limit], construct or filter the graph adjacency list keeping only edges where weight < limit. Then, run standard BFS or DFS starting from node p to see if q is reachable.
Because BFS takes O(V + E) time per query, processing Q queries requires O(Q \cdot (V + E)) time, which is too slow for large inputs.
When to apply: Viable only when the number of queries is very small (Q <= 50).
Algorithm
- Step 1: Iterate through each query [p, q, limit].
- Step 2: Initialize a queue with node p and a visited array of size n.
- Step 3: Perform BFS considering only adjacent edges with weight < limit.
- Step 4: If node q is reached, mark result for this query as true; otherwise, false upon queue exhaustion.
- Step 5: Return the boolean answer array.
#include <iostream>#include <vector>#include <queue> std::vector<bool> solveBruteForce(int n, const std::vector<std::vector<int>>& edges, const std::vector<std::vector<int>>& queries) { std::vector<std::vector<std::pair<int, int>>> adj(n); for (const auto& e : edges) { adj[e[0]].push_back({e[1], e[2]}); adj[e[1]].push_back({e[0], e[2]}); } std::vector<bool> ans; ans.reserve(queries.size()); for (const auto& q : queries) { int start = q[0], target = q[1], limit = q[2]; std::vector<bool> visited(n, false); std::queue<int> qu; qu.push(start); visited[start] = true; bool found = false; while (!qu.empty()) { int u = qu.front(); qu.pop(); if (u == target) { found = true; break; } for (const auto& edge : adj[u]) { int v = edge.first; int w = edge.second; if (w < limit && !visited[v]) { visited[v] = true; qu.push(v); } } } ans.push_back(found); } return ans;} int main() { int n = 3; std::vector<std::vector<int>> edges = {{0, 1, 2}, {1, 2, 4}, {2, 0, 8}}; std::vector<std::vector<int>> queries = {{0, 2, 5}, {0, 2, 3}}; auto res = solveBruteForce(n, edges, queries); for (bool b : res) std::cout << (b ? "true " : "false "); std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(Q * (V + E)) where Q is queries, V is vertices, E is edges - Space complexity:
O(V + E) for the adjacency list and visited set