ghostmkg / programming-language

You write code in any programming language you want. And push the code.
33 stars 79 forks source link

Contribution for Hackertoberfest2024 : a_star_algorithm.py #21

Closed 0mehedihasan closed 6 days ago

0mehedihasan commented 6 days ago

Explanation:

  1. Graph Representation: The graph is represented as an adjacency list where each node maps to a list of tuples. Each tuple contains a neighboring node and the cost to reach that neighbor.

  2. Priority Queue: The algorithm uses a priority queue (open_list) to keep track of nodes to explore, prioritizing the node with the smallest f(n) = g(n) + h(n).

  3. Heuristic Function: The heuristic() function provides an estimated cost to reach the goal from any given node. In this case, a simple dictionary is used, which can be adjusted depending on the problem (e.g., Euclidean or Manhattan distances).

  4. Algorithm Logic:

The algorithm starts by initializing the priority queue with the start node and its heuristic value.

It pops the node with the lowest f(n) from the queue.

If the goal is reached, it returns the path and the total cost.

Otherwise, it explores all neighboring nodes, calculates their g(n) and f(n) values, and adds them to the queue if they haven't been visited yet.

Output:

For the graph in this example, the output will look like this:

Shortest path: ['A', 'B', 'D', 'E', 'G'] Total cost: 6