Implementation of Depth-first search

 Here is an example implementation of Depth-First Search (DFS) algorithm in Python:

def dfs(graph, start, goal): visited = set() stack = [(start, [start])] while stack: (vertex, path) = stack.pop() if vertex not in visited: if vertex == goal: return path visited.add(vertex) for neighbor in graph[vertex]: stack.append((neighbor, path + [neighbor])) return None


In this implementation, graph is a dictionary representing the graph, start is the starting node, and goal is the goal node. The algorithm uses a stack to keep track of the nodes to be visited. It starts with the starting node and its path, and then iteratively adds its neighbors to the stack until it reaches the goal node or there are no more nodes to visit. If the goal node is found, the algorithm returns the path to the goal node. If the goal node is not found, the algorithm returns None.

Note that this implementation of DFS does not consider the cost of the actions. If the cost of the actions is important, you may want to use another algorithm such as Uniform-Cost Search or A* Search instead.



Comments

Popular posts from this blog

OpenSolaris and Linux virtual memory and address space structures

Tagged architectures and multi-level UNIX

Tying top-down and bottom-up object and memory page lookups with the actual x86 page translation and segmentation