Leetcode 1971. Find if Path Exists in Graph
You are given an undirected graph of n nodes labeled from 0 to n - 1 and an integer n representing the number of nodes. You are also given a 2D array edges, where edges[i] = [a_i, b_i] indicates that there is an undirected edge between nodes a_i and b_i. Given two integers source and destination, return true if there is a valid path from source to destination, or false otherwise.
n, 1 <= n <= 200000.edges.length, 0 <= edges.length <= 200000.edges[i][0] and edges[i][1] will fall within [0, n-1].source is the same as destination, should we return true? Yes.source is not equal to destination? false.Here’s the Java code to solve the problem:
import java.util.*;
public class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
if (source == destination) {
return true;
}
// Create an adjacency list
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
// Implement BFS
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.offer(source);
visited.add(source);
while (!queue.isEmpty()) {
int currentNode = queue.poll();
for (int neighbor : graph.get(currentNode)) {
if (neighbor == destination) {
return true;
}
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.offer(neighbor);
}
}
}
return false;
}
}
O(V + E) where V is the number of vertices (n) and E is the number of edges.O(V + E) since each node and edge is processed once in BFS.Overall, the time complexity is O(V + E), making this approach efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?