stack = [] def DFS(): def findpath(): global pos global dest global stack # This eats O(intersections) stack val = valid(neighbours0(pos[0],pos[1])) try: val.remove(stack[-1]) except IndexError: # Should possibly only happen on the first entry pass if val: stack.append(pos) for path in val: pos = path search(path) if pos == dest or findpath(): return True pos = stack.pop() return False findpath()