Tracing and Returning a Path in Depth First Search

2024/11/19 21:25:20

So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function:

    start = problem.getStartState()stack = Stack()visited = []stack.push(start)if problem.isGoalState(problem.getStartState):return somethingwhile stack:parent = stack.pop()if parent in visited: continueif problem.isGoalState(parent):return somethingvisited.append(parent)children = problem.getSuccessors(parent)for child in children:stack.push(child[0])

The startState and goalState variables are simply a tuple of x, y coordinates. problem is a class with a variety of methods. The important ones here are getSuccessors (which returns the children of a given state in the form of a list of 3 item tuples. for this part of the problem though, only the first element of the tuple, (child[0]), which returns the state of the child in x, y coordinates, is important) and isGoalState (which provides the x, y coordinates of the goal state).

So I THINK (difficult to test at this point), that this function, given proper implementation of everything else, will return once it has reached a goal state. Please let me know if I am missing something. My biggest issue, though, is WHAT to return. I want it to output a list of all of the states it takes to get to the goal state, in order from the beginning to the end. It doesn't seem like simply returning my stack will do the trick, since the stack will include many unvisited children. Nor will my visited list yield anything useful, since it is conceivable I could reach dead ends, have to backtrack, but still have the dead-end tuples in the visited list. How would I go about getting the list I desire?

Answer

You are right - you cannot simply return the stack, it indeed contains a lot of unvisited nodes.

However, by maintaining a map (dictionary): map:Vertex->Vertex such that parentMap[v] = the vertex we used to discover v, you can get your path.

The modification you will need to do is pretty much in the for loop:

    for child in children:stack.push(child[0])parentMap[child] = parent #this line was added

Later on, when you found your target, you can get the path from the source to the target (pseudo code):

curr = target
while (curr != None):print currcurr = parentMap[curr]

Note that the order will be reversed, it can be solved by pushing all elements to a stack and then print.

I once answered a similar (though not identical IMO) question regarding finding the actual path in BFS in this thread

Another solution is to use a recursive version of DFS rather then iterative+stack, and once a target is found, print all current nodes in the recursion back up - but this solution requires a redesign of the algorithm to a recursive one.


P.S. Note that DFS might fail to find a path to the target (even if maintaining a visited set) if the graph contains an infinite branch.
If you want a complete (always finds a solution if one exists) and optimal (finds shortest path) algorithm - you might want to use BFS or Iterative Deepening DFS or even A* Algorithm if you have some heuristic function

https://en.xdnf.cn/q/26389.html

Related Q&A

Pandas OHLC aggregation on OHLC data

I understand that OHLC re-sampling of time series data in Pandas, using one column of data, will work perfectly, for example on the following dataframe:>>df ctime openbid 1443654000 1.1170…

Python plotting libraries [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

python elasticsearch client set mappings during create index

I can set mappings of index being created in curl command like this:{ "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true"},"properties&…

Get Primary Key after Saving a ModelForm in Django

How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the …

f.write vs print f

There are at least two ways to write to a file in python:f = open(file, w) f.write(string)orf = open(file, w) print >> f, string # in python 2 print(string, file=f) # in python 3Is there a d…

How can I send a message to someone with my telegram bot using their Username

I am using the telepot python library, I know that you can send a message when you have someones UserID(Which is a number). I wanna know if it is possible to send a message to someone without having th…

Convert a str to path type?

I am trying to interface with some existing code that saves a configuration, and expects a file path that is of type path.path. The code is expecting that the file path is returned from a pygtk browse…

Partially transparent scatter plot, but with a solid color bar

In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1?Here is what one gets, with from…

Semaphores on Python

Ive started programming in Python a few weeks ago and was trying to use Semaphores to synchronize two simple threads, for learning purposes. Here is what Ive got: import threading sem = threading.Semap…

Overload () operator in Python

I am trying to learn currying in Python for my class and I have to overload the () operator for it. However, I do not understand how can I can go about overloading the () operator. Can you explain the …