0% found this document useful (0 votes)
19 views3 pages

Best FS

The document describes the implementation of the Best-First Search algorithm to find the shortest path in a graph represented as an adjacency list. It outlines the steps of initializing the frontier, exploring nodes, updating costs, and reconstructing the path. An example usage is provided, demonstrating how to find the shortest path from node 'A' to node 'F'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views3 pages

Best FS

The document describes the implementation of the Best-First Search algorithm to find the shortest path in a graph represented as an adjacency list. It outlines the steps of initializing the frontier, exploring nodes, updating costs, and reconstructing the path. An example usage is provided, demonstrating how to find the shortest path from node 'A' to node 'F'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 3

In this implementation, the best_first_search function takes the starting node, the goal node, and the

graph represented as an adjacency list. It uses a PriorityQueue to maintain the frontier, where the
priority is the estimated cost from the start node to the current node.

The algorithm works as follows:

1. Initialize the frontier with the starting node and its cost (0).

2. Initialize the came_from and cost_so_far dictionaries to keep track of the path and the costs.

3. While the frontier is not empty:

o Pop the node with the lowest estimated cost from the frontier.

o If the current node is the goal, break out of the loop.

o For each neighbor of the current node:

 Calculate the new cost to reach the neighbor.

 If the neighbor is not in the cost_so_far dictionary or the new cost is lower
than the current cost, update the cost_so_far dictionary and add the
neighbor to the frontier with the new priority.

 Update the came_from dictionary to keep track of the path.

4. Reconstruct the path from the goal to the start by following the came_from dictionary.

5. Return the path, or None if no path is found.

You can use this implementation by providing a graph and the start and goal nodes. The function will
return the shortest path from the start to the goal, or None if no path is found.

from queue import PriorityQueue

def best_first_search(start, goal, graph):


"""
Performs Best-First Search on a given graph to find the shortest path from
start to goal.

Args:
start (str): The starting node.
goal (str): The goal node.
graph (dict): The graph represented as an adjacency list, where the keys
are nodes
and the values are lists of (neighbor, cost) tuples.

Returns:
list: The shortest path from start to goal, or None if no path is found.
"""
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()

if current == goal:
break

for next_node, cost in graph[current]:


new_cost = cost_so_far[current] + cost
if next_node not in cost_so_far or new_cost < cost_so_far[next_node]:
cost_so_far[next_node] = new_cost
priority = new_cost
frontier.put(next_node, priority)
came_from[next_node] = current

# Reconstruct the path


path = []
current = goal
while current != start:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()

if len(path) == 1 and path[0] == start:


return None
else:
return path

# Example usage
graph = {
'A': [('B', 5), ('C', 1)],
'B': [('A', 5), ('C', 2), ('D', 1)],
'C': [('A', 1), ('B', 2), ('D', 4), ('E', 8)],
'D': [('B', 1), ('C', 4), ('E', 3), ('F', 6)],
'E': [('C', 8), ('D', 3), ('F', 3)],
'F': [('D', 6), ('E', 3)]
}

start = 'A'
goal = 'F'
path = best_first_search(start, goal, graph)

if path:
print(f"The shortest path from {start} to {goal} is: {' -> '.join(path)}")
else:
print(f"No path found from {start} to {goal}")

graph = {

'A': [('B', 5), ('C', 1)],

'B': [('A', 5), ('C', 2), ('D', 1)],

'C': [('A', 1), ('B', 2), ('D', 4), ('E', 8)],

'D': [('B', 1), ('C', 4), ('E', 3), ('F', 6)],

'E': [('C', 8), ('D', 3), ('F', 3)],

'F': [('D', 6), ('E', 3)] }


We want to find the shortest path from node 'A' to node 'F'.

Let's run the best_first_search function with the given inputs:

python

start = 'A'

goal = 'F'

path = best_first_search(start, goal, graph)

if path:

print(f"The shortest path from {start} to {goal} is: {' -> '.join(path)}")

else:

print(f"No path found from {start} to {goal}")

The output will be:

rust

The shortest path from A to F is: A -> C -> D -> E -> F

Here's how the algorithm works step-by-step:

1. The frontier is initialized with the starting node 'A' and its cost of 0.

2. The algorithm explores the neighbors of 'A': 'B' with cost 5 and 'C' with cost 1. 'C' is added to
the frontier with priority 1.

3. The node with the lowest cost ('C') is removed from the frontier. Its neighbors are explored:
'A' (already visited), 'B' with cost 2, 'D' with cost 4, and 'E' with cost 8. 'B' and 'D' are added to
the frontier.

4. The node with the lowest cost ('B') is removed from the frontier. Its neighbors are explored:
'A' (already visited), 'C' (already visited), and 'D' with cost 1. 'D' is added to the frontier.

5. The node with the lowest cost ('D') is removed from the frontier. Its neighbors are explored:
'B' (already visited), 'C' (already visited), 'E' with cost 3, and 'F' with cost 6. 'E' is added to the
frontier.

6. The node with the lowest cost ('E') is removed from the frontier. Its neighbors are explored:
'C' (already visited), 'D' (already visited), and 'F' with cost 3. 'F' is added to the frontier.

7. The node with the lowest cost ('F') is removed from the frontier, and since it's the goal node,
the algorithm stops.

8. The path is reconstructed by following the came_from dictionary: 'A' -> 'C' -> 'D' -> 'E' -> 'F'.

The final output is the shortest path from 'A' to 'F': 'A -> C -> D -> E -> F'.

You might also like