DevPath

← All problems

Find a Path in a Graph

Medium graphs · bfs

Description

Given n nodes, an undirected edge list, a source and a destination, return true if a path exists.

Constraints

1 <= n <= 100000

Examples

Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], src = 0, dst = 5

Output: false

Hints (1)
  • Flood fill from the source and check whether the destination is reached.

Solutions

DFS from source. · Time O(V+E) · Space O(V+E)

func hasPath(n int, edges [][]int, src, dst int) bool {
    adj := make([][]int, n)
    for _, e := range edges {
        adj[e[0]] = append(adj[e[0]], e[1])
        adj[e[1]] = append(adj[e[1]], e[0])
    }
    seen := make([]bool, n)
    stack := []int{src}
    for len(stack) > 0 {
        u := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if u == dst {
            return true
        }
        if seen[u] {
            continue
        }
        seen[u] = true
        for _, v := range adj[u] {
            if !seen[v] {
                stack = append(stack, v)
            }
        }
    }
    return false
}

Create a free account to submit solutions, track progress and save problems.

Create account