2

I am trying to find the shortest path on a grid(list of lists of tuples) I've gotten this so far:

def planPath(self, x, y, goal, board):
    visited = []
    path = []
    def pathFinder(curr):
        visited.append(curr)
        neighbors = None
        if curr == goal:
            visited.append(curr)
            return curr
        neighbors = [neighbor for neighbor in curr.neighbors if type(neighbor) is not Land.Water and neighbor not in visited]
        neighbors.sort(key=lambda neighbor:  abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation), reverse=False)

x, y are the current location, is obvious, and board is, well the entire board. The thought was that it would be recursive. For every call I would get the neighbors for the current node, filter out the water(untravelable) and the visited. Then sort by the closest to the goal. Next I want to go through and do a breadth first search. So I will expand all the neighbors, then expand each of their neighbors and so on. Each branch would go on until they have no neighbors, they would return None and be done with. Then end result being that the only one to return will be the first brach to reach the goal, i.e. the shortest. Does anyone know how I could do this?

I was thinking this:

for neighbor in neighbors:
    next = pathFinder(neighbor)
    if next:
        visited.append(cure)
        return curr
    else: return None

but, correct me if I'm wrong, but that would result in depth first search, not breadth.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
EasilyBaffled
  • 3,822
  • 10
  • 50
  • 87
  • Your indentation is all over the map (mixing tabs and spaces is never a good idea). I did my best to fix things, can you verify your post? – Martijn Pieters Apr 02 '13 at 20:31
  • 5
    Recursion is not a natural fit for a breadth-first search. It makes much more sense if you're doing a depth-first search, since the call stack helps you keep track of the locations you've visited so far. For a breadth-first search you want to be using a queue instead. See [this related question](http://stackoverflow.com/questions/2549541/performing-breadth-first-search-recursively) for more discussion. – Blckknght Apr 02 '13 at 21:21
  • As @Blckknght said, breadth first search is easy to implement with a "while-queue-not-empty-loop" (see python [deque](http://docs.python.org/2/library/collections.html#collections.deque) structure) where you push unvisited neighbors. – Maxime Apr 02 '13 at 22:22
  • http://en.wikipedia.org/wiki/A*_search_algorithm – user1149913 Apr 03 '13 at 04:48

1 Answers1

-4

The following is the pseudo code that could help you

BFS(v)
    let neighbors be the set of all neighbours of vertex v
    for neighbor in neighbors:
        if neighbor is not visited:
            visit neighbour
    for neighbor in neighbors:
        recurisvely call BFS(neighbor)
Ashok
  • 93
  • 1
  • 1
  • 9