4

Here is the graph:

g = {
    0: [2, 5, 7],
    1: [7],
    2: [0, 6],
    3: [5, 4],
    4: [3, 6, 7],
    5: [3, 4, 0],
    6: [2, 4],
    7: [0, 1, 4]
}

enter image description here

I have the following function in Python:

def dfs(graph, start, target, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)

    for n in (set( graph[start] ) - visited):
        dfs(graph, n, target, visited)
    return visited

But it returns all the vertices that exists in the graph, and I want that it returns just the target vertex if it's present in the graph. Could someone help me?

Dominique Fortin
  • 2,212
  • 15
  • 20
Patterson
  • 326
  • 1
  • 7
  • 19

1 Answers1

1

You want to test if you reached your target and, if you did, return True. This can be accomplished by making the following edits to your code:

Small edit for efficiency

def dfs(graph, start, target, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)

    for n in (set( graph[start] ) - visited):
        if n == target:
            return True
        return dfs(graph, n, target, visited)
    return False

Edit: I made a mistake in my algorithm, fixed version is below:

def dfs(graph, start, target, visited=None):
    if start == target:
        return True
    if visited is None:
        visited = set()
    visited.add(start)

    found = False
    for n in (set( graph[start] ) - visited):
        if target == n:
            return True
        found = dfs(graph, n, target, visited)
    return found
Brian
  • 1,659
  • 12
  • 17