Introduction.
Unveiling the power of Non-Linear Search.
Implementing Depth-First Search in Python
Let's take a look at a Python implementation of the Depth-First Search algorithm:
pythonfrom collections import defaultdict
def dfs(graph, start, target, visited=None):
"""
Perform a depth-first search to find the target node in a graph.
Parameters:
graph (dict): The graph represented as an adjacency list.
start (any): The starting node.
target (any): The target node to search for.
visited (set, optional): The set of visited nodes.
Returns:
bool: True if the target is found, False otherwise.
"""
if visited is None:
visited = set()
# Mark the current node as visited
visited.add(start)
# Check if the current node is the target
if start == target:
return True
# Recursively search the neighbors
for neighbor in graph[start]:
if neighbor not in visited and dfs(graph, neighbor, target, visited):
return True
return False
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
start_node = 'A'
target_node = 'F'
if dfs(graph, start_node, target_node):
print(f"Target node '{target_node}' found!")
else:
print(f"Target node '{target_node}' not found.")
In this example, we implement the Depth-First Search algorithm to search for a target node in a graph. The dfs function takes the graph, the starting node, the target node, and an optional set of visited nodes. It recursively explores the graph, marking each visited node and checking if the current node is the target. If the target is found, the function returns True; otherwise, it returns False.
While DFS and other graph-based algorithms are powerful non-linear search techniques, there are also alternatives that leverage different data structures, such as hash tables which we will talk in the next blog. Hash-based search algorithms use a hash function to map data elements to specific locations within a hash table, allowing for constant-time lookups in many cases.

No comments:
Post a Comment