How to get the shortest path? A clever problem-solver, however, if you use the Greedy Best-First Search (GBFS) algorithm, you are willing to help. Think of it as that one friend who always puts the best foot forward. In this series of articles, I will explain Greedy Best-First Search and show examples using Python code. In this blog post, Let us see the wonders of Greedy Best-First Search while it makes smart choices and when it is apt for the job.
Here’s a simple way to understand the GBFS algorithm:
Sounds simple, right? But there’s a catch! The GBFS algorithm doesn’t always find the shortest path because it only looks at what seems best right now, not considering the whole journey.
Let’s see an example using a simple grid. Imagine we have a 4×4 grid, and we want to go from the top-left corner (0, 0) to the bottom-right corner (3, 3). Here’s the grid with some obstacles:
[ [0, 1, 1, 1]
[1, 0, 1, 1]
[1, 0, 0, 1]
[1, 1, 0, 0] ]
In this grid, 1 means you can’t go through that cell, and 0 means you can. We’ll use the Euclidean distance as our heuristic, which is just a fancy way of saying the straight-line distance to the goal.
Here’s how we can write the Greedy Best-First Search algorithm in Python.
Python Code:
import heapq
import math
class Node:
def __init__(self, x, y, cost):
self.x = x
self.y = y
self.cost = cost
def __lt__(self, other):
return self.cost < other.cost
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
def greedy_best_first_search(grid, start, goal):
rows = len(grid)
cols = len(grid[0])
pq = []
heapq.heappush(pq, Node(start[0], start[1], 0))
visited = set()
visited.add((start[0], start[1]))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while pq:
current = heapq.heappop(pq)
if (current.x, current.y) == goal:
print(f"Goal reached at ({current.x}, {current.y})")
return
for d in directions:
new_x, new_y = current.x + d[0], current.y + d[1]
if 0 <= new_x < rows and 0 <= new_y < cols and grid[new_x][new_y] == 0 and (new_x, new_y) not in visited:
cost = euclidean_distance(new_x, new_y, goal[0], goal[1])
heapq.heappush(pq, Node(new_x, new_y, cost))
visited.add((new_x, new_y))
print("Goal not reachable")
# Example grid
grid = [
[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 0, 0, 1],
[1, 1, 0, 0]
]
start = (0, 0)
goal = (3, 3)
greedy_best_first_search(grid, start, goal)
When you run this code, it starts from the top-left corner (0, 0) and tries to move to the bottom-right corner (3, 3). It picks the next step based on which one looks closest to the goal using the Euclidean distance.
Advantages:
Disadvantages:
The Greedy Best-First Search algorithm provides a valuable technique for tackling pathfinding problems in grids or graphs. Its strength lies in rapidly identifying promising routes toward the goal by leveraging a well-designed heuristic function. However, it’s crucial to understand that the GBFS approach does not guarantee finding the optimal, shortest path. Its greedy nature may sometimes lead it astray if the heuristic is imperfect or misleading.
Despite this limitation, the algorithm’s simplicity, efficiency, and ability to produce reasonably good solutions quickly make it a valuable tool for programmers, particularly in time-sensitive situations where a near-optimal solution is preferable to an exhaustive but computationally expensive search for the absolute shortest path. Careful implementation and heuristic design can help harness the power of GBFS for a wide range of pathfinding challenges.
A. The Greedy Best-First Search algorithm is a pathfinding technique that selects the next move based on which option appears closest to the goal, using a heuristic to guide its decisions.
A. Unlike algorithms like A* that consider both the current cost and the estimated cost to the goal, GBFS focuses only on the heuristic estimate to the goal, making it faster but not always optimal.
A. No, GBFS does not guarantee the shortest path because it only considers the heuristic estimate and not the overall cost from the start to the goal.
Seasoned AI enthusiast with a deep passion for the ever-evolving world of artificial intelligence. With a sharp eye for detail and a knack for translating complex concepts into accessible language, we are at the forefront of AI updates for you. Having covered AI breakthroughs, new LLM model launches, and expert opinions, we deliver insightful and engaging content that keeps readers informed and intrigued. With a finger on the pulse of AI research and innovation, we bring a fresh perspective to the dynamic field, allowing readers to stay up-to-date on the latest developments.
Gradient Boosting Algorithm: A Complete Guide f...
Best First Search in Artificial Intelligence
Introduction to Intelligent Search Algorithms
Informed Search Strategies for State Space Sear...
An Introduction to Problem-Solving using Search...
What is A* Algorithm?
Uninformed Search Strategy for State Space Sear...
What is Heuristic Function in AI?
Uniform Cost Search Algorithm
Dijkstra Algorithm in Python
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
It is needed for personalizing the website.
Expiry: Session
Type: HTTP
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Expiry: Session
Type: HTTPS
Preserves the login/logout state of users across the whole site.
Expiry: Session
Type: HTTPS
Preserves users' states across page requests.
Expiry: Session
Type: HTTPS
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
Expiry: 365 days
Type: HTTP
Used by Microsoft Clarity, to store and track visits across websites.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
Expiry: 1 Day
Type: HTTP
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Years
Type: HTTP
Use to measure the use of the website for internal analytics
Expiry: 1 Years
Type: HTTP
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
Expiry: 1 Year
Type: HTTP
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Months
Type: HTTP
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics, to store and count pageviews.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
Expiry: 1 Day
Type: HTTP
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
Expiry: Session
Type: PIXEL
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
Expiry: 6 Months
Type: HTTP
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
Expiry: 2 Years
Type: HTTP
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
Expiry: 1 Year
Type: HTTP
this is used to send push notification using webengage.
Expiry: 1 Year
Type: HTTP
used by webenage to track auth of webenagage.
Expiry: Session
Type: HTTP
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
Expiry: 1 Day
Type: HTTP
Use to maintain an anonymous user session by the server.
Expiry: 1 Year
Type: HTTP
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
Expiry: 1 Year
Type: HTTP
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
Expiry: 6 Months
Type: HTTP
allow for the Linkedin follow feature.
Expiry: 1 Year
Type: HTTP
often used to identify you, including your name, interests, and previous activity.
Expiry: 2 Months
Type: HTTP
Tracks the time that the previous page took to load
Expiry: Session
Type: HTTP
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
Expiry: Session
Type: HTTP
Tracks percent of page viewed
Expiry: Session
Type: HTTP
Indicates the start of a session for Adobe Experience Cloud
Expiry: Session
Type: HTTP
Provides page name value (URL) for use by Adobe Analytics
Expiry: Session
Type: HTTP
Used to retain and fetch time since last visit in Adobe Analytics
Expiry: 6 Months
Type: HTTP
Remembers a user's display preference/theme setting
Expiry: 6 Months
Type: HTTP
Remembers which users have updated their display / theme preferences
Expiry: 6 Months
Type: HTTP
Used by Google Adsense, to store and track conversions.
Expiry: 3 Months
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 6 Hours
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 1 Month
Type: HTTP
These cookies are used to gather website statistics, and track conversion rates.
Expiry: 1 Month
Type: HTTP
Aggregate analysis of website visitors
Expiry: 6 Months
Type: HTTP
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
Expiry: 4 Months
Type: HTTP
Contains a unique browser and user ID, used for targeted advertising.
Expiry: 2 Months
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 1 Year
Type: HTTP
Used by LinkedIn for tracking the use of embedded services.
Expiry: 1 Day
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 6 Months
Type: HTTP
Use these cookies to assign a unique ID when users visit a website.
Expiry: 6 Months
Type: HTTP
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
Expiry: 6 Months
Type: HTTP
Used to make a probabilistic match of a user's identity outside the Designated Countries
Expiry: 90 Days
Type: HTTP
Used to collect information for analytics purposes.
Expiry: 1 year
Type: HTTP
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
Expiry: 1 Day
Type: HTTP
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
Edit
Resend OTP
Resend OTP in 45s