Grokking the Coding Interview: The Original Course
Vote

0% completed

​

Solution: Find if Path Exists in Graph (easy)

Problem Statement

You are given an undirected graph, represented as a list of edges. Each edge is a pair of integers [u, v], which means that node u and node v are connected in both directions.

You are also given a starting node start and a destination node end. Return true if a path exists between the starting node and the destination node. Otherwise, return false.

Examples

Example 1:

  • Input: n = 4, edges = [[0,1],[1,2],[2,3]], start = 0, end = 3
  • Expected Output: true
    • Justification: There's a path from node 0 -> 1 -> 2 -> 3

.....

.....

.....

Like the course? Get enrolled and start learning!
Zakaria Faddi

Zakaria Faddi

· 6 days ago

from collections import defaultdict class Solution: def validPath(self, n: int, edges: [[int]], start: int, end: int) -> bool: # build the graph from edges def buildGraph(edges): for node1 , node2 in edges: adjacency_list[node1].append(node2) adjacency_list[node2].append(node1) # depth first search into the node to find the validPath def DFS(graph, start, stop): if start in visited: return False if start == stop: return True visited.add(start) for node in graph[start]: if DFS(graph, node, stop): return True return False adjacency_list = defaultdict(list) buildGraph(edges)
M

mosharaf.hossain221

· 10 days ago

def validPath(self, n: int, edges: [[int]], start: int, end: int) -> bool:         if not edges:             return False         if start == end:             return True         graph = defaultdict(list)         for u, v in edges:             graph[u].append(v)             graph[v].append(u)         visited = set([start])         q = deque([start])         while q:             node = q.popleft()             if node == end:                 return True             for nei in graph[node]:                 if nei not in visited:                     visited.add(nei)                     q.append(nei)         return False;
Massi Faqiri

Massi Faqiri

· a month ago

With n up to 200,000, recursion implementation of DFS can lead to overflow. I think this solution would be better off with BFS or stack-based DFS.

Show 1 reply
Raul Acosta

Raul Acosta

· 2 years ago

The solution returns true at n = 1, but there can be no self-edges. This should return false.

Show 2 replies
Elena Feoktistova

Elena Feoktistova

· 3 years ago

import java.util.*; public class Solution { private boolean[] visited; // To keep track of visited nodes public boolean validPath(int n, int[][] edges, int start, int end) { if (edges.length == 0) return false; visited = new boolean[n]; visited[edges[0][0]] = true; for (int i = 0; i < edges.length; i++) { if (visited[edges[i][0]] == true) { visited[edges[i][1]] = true; } } return visited[start] == true && visited[end] == true; } }
Show 2 replies

Reading Progress

0%


Vote for new content