I have a 2d array arr
where each cell in it has a value 1, 2 or 3 for example arr[0][0] = 3, arr[2][1] = 2 and arr[0][4] = 1
. I want to know the shortest path from a given certain cell eg arr[5][5]
to the closest cell which has value 2 where the path shouldn't contain any cells that have the value 1. Any advice?
Below is a the script for the BFS but I don't know how I can make it accept a 2d array as graph and starting point as a certain cell location in the array and then go to the nearest 2 from this cell avoiding cells with 1s, so that it looks like bfs(2darray, starting location, 2)?
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
# path found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print bfs(graph, '1', '11')
You can use a simple breadth first search for this. Basically, each cell in your grid corresponds to a node in the graph, with edges between adjacent cells. Start at the starting position, and keep expanding passable cells until you find a goal cell.
Grid setup and results: (Note that I'm using symbols instead of numbers, simply for the reason that it's easier to visually parse the grid this way and to very the solution.)
If the list is not too big, the easiest solution I find is using the where function of the numpy library to find the cells which have the value you are looking for. So, you will need to convert your list into a numpy array.
The code below might be simplified to make it shorter and more efficient, but in this way it will be clearer. By the way, you can compute two kind of distances: the typical euclidean and the manhattan.
If there is more than one target cell at the same distance of the origin cell, min_coords corresponds to the first cell found (first by rows, then by columns).