The code is to find a path in a square maze from the start 'A' to the end 'B': The core function is:
def searchFrom(self, row, column):
if self.laby[row][column] == OBSTACLE: # obstacle
return False
if self.laby[row][column] == TRIED or self.laby[row][column] == DEAD_END:
return False
if self.laby[row][column] == END:
self.path.push((row, column))
self.isFound = True
return True
self.laby[row][column] = TRIED
isFound = self.searchFrom(row-1, column) or \
self.searchFrom(row+1, column) or \
self.searchFrom(row, column-1) or \
self.searchFrom(row, column+1)
if isFound:
self.path.push((row, column))
else:
self.laby[row][column] = DEAD_END
return isFound
In this case, what's the O(n) for this recursive algorithm.
My understanding is:
T(n) = 13+4T(n-1) = 13+4(13+4T(n-2)) = ... = 13(4^0+4^1+4^2+...+4^(n-1))+T(0)
so, the Big O is:
O(4^n)
Is this correct?
What is the fast algorithm to find a path in maze? DFS or BFS or some else?
I don't think that's correct.
Yes, thinking locally , you have a potential fan-out of 4 at each node of your search. However, globally , you cannot visit more than n^2
locations. At the leaf node, you will return in O(1) time, rather than fanning out. You can have no more than n^2
calls that do not return in O(1) time.
As for depth-first vs breadth-first, consider your maze as a tree-structure graph with only one goal state at a leaf node. The worst case search in either DFS or BFS is having to visit all nodes. Since you know that you need to find a leaf node of the structure, the average case will make DFS slightly faster: BFS is guaranteed to visit unproductive intermediate nodes before finding the solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.