Python Forum
Requesting help with my implementation of depth-first search
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Requesting help with my implementation of depth-first search
#4
Look at the first wrong edge in the output: (3, 4). There is no such edge in your graph. How did it get that? When you add (1, 3), you change w to 3, but your for loop is still looping over the edges from 1. The next edge is (1, 4), but since you've changed w to 3, it stores it as (1, 4).

I don't understand how this algorithm is supposed to be working. I skipped that chapter when I read Discrete Mathematics because I'd done it with Introduction to Algorithms. That book uses a recursive search, which was my first instinct. I think to get it working without recursion you are going to have to reset your tracking variables a lot. When you change w, you have to change the list of edges you are going through. And when you go back after hitting a dead end I think you will need to reset i as well.

Edit: This gets the correct list of edges, just in a different order, and without recursion. It could probably be more efficient.

input_graph = {1:[3,4,8,9,11], 2:[3,8,12], 3:[1,2,5,11], 4:[1,6,9,10], 5:[3,12], 6:[4,10], 7:[8,12],
    8:[1,2,7,10], 9:[1,4,11], 10:[4,6,8], 11:[1,3,9], 12:[2,5,7]}

def DFS(graph, root):
    visited = set([root])
    current = root
    edges = []
    while len(visited) < len(graph):
        possible = [node for node in graph[current] if node not in visited]
        if possible:
            edges.append((current, possible[0]))
            visited.add(possible[0])
            current = possible[0]
        else:
            current = [start for start, end in edges if end == current][0]
    return edges

print(DFS(input_graph, 1))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: Requesting help with my implementation of depth-first search - by ichabod801 - Sep-25-2019, 01:56 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Max recursion depth.... Error MeloB 2 1,976 Feb-16-2022, 05:21 PM
Last Post: MeloB
  requesting help for a faster alternative of pd.groupby zollen 1 1,723 Jul-07-2021, 06:33 PM
Last Post: ndc85430
Bug maximum recursion depth exceeded while calling a Python object error in python3 Prezess 4 3,831 Aug-02-2020, 02:21 PM
Last Post: deanhystad
  Requesting help with 3D plotting with quivers Akan2019 1 1,652 May-15-2019, 07:46 AM
Last Post: Akan2019
  RecursionError: maximum recursion depth exceeded in comparison ? leoahum 11 13,234 Mar-18-2019, 01:53 PM
Last Post: leoahum
  variable loop depth Skaperen 5 4,439 Jul-18-2018, 02:48 AM
Last Post: Skaperen
  maximum recursion depth exceeded saba_keon 3 7,534 Apr-08-2018, 07:30 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020