Eren
Eren

Reputation: 3

Iterative into Recursive

Hi everyone, I'm stuck on an assignment and i want to ask a question. My aim is finding all possible routes between the starter(start) and target(end) node. I'm working on this code and its graph: Note: Values in dictionary show the neighbours of keys.

import sys
graph={'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'], 'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if start not in graph:
        return None
    paths = []
    for node in graph[start]:
        if node not in path:
            try:
                newpaths = find_all_paths(graph, node, end, path)
                for newpath in newpaths:
                    paths.append(newpath)
            except TypeError:
                print("No road")
                sys.exit()
    return paths

I want this to be a completely recursive function(there should be no "for" loops).I've tried many things but I failed every time. Do u have any suggestions ?

Upvotes: 0

Views: 66

Answers (1)

gil.fernandes
gil.fernandes

Reputation: 14611

You can use depth first search for navigating safely through the graph. This uses recursion and avoids infinite loops using the marked map:

marked = {}


def navigate(graph):
    v, *tail = graph
    iterate(v, tail) # recursive for loop replacement


def iterate(v, elements):
    if v is not None:
        if v not in marked:
            dfs(graph, v)
        if len(elements) > 0:
            v, *tail = elements
            iterate(v, tail)


def dfs(graph, v):
    print(v)  # do something with the node
    marked[v] = True
    w, *tail = graph[v]
    iterate_edges(w, graph[v])


def iterate_edges(w, elements):
    if w is not None:
        if w not in marked:
            dfs(graph, w)
        if len(elements) > 0:
            v, *tail = elements
            iterate(v, tail)


graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
         'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

navigate(graph)

To be honest, I prefer an implementation with some loops, because then the code is more readable:

marked = {}


def navigate(graph):
    for v in graph:
        if v not in marked:
            dfs(graph, v)


def dfs(graph, v):
    print (v)
    marked[v] = True
    for w in graph[v]:
        if w not in marked:
            dfs(graph, w)


graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
         'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

navigate(graph)

The output of both variants is:

x1
x2
x4
x5
x7
x9
x3
x6
x8

Upvotes: 1

Related Questions