Prerequisites : BFS, DFS

In BFS and DFS, when we are at a node, we can consider any of the adjacent as next node. So both BFS and DFS blindly explore paths without considering any cost function. The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuristic Search or Informed Search.

We use a priority queue to store costs of nodes. So the implementation is a variation of BFS, we just need to change Queue to PriorityQueue.

// This pseudocode is adapted from below // source: // https://courses.cs.washington.edu/Best-First-Search(Grah g, Node start) 1) Create an empty PriorityQueue PriorityQueuepq; 2) Insert "start" in pq. pq.insert(start) 3) Until PriorityQueue is empty u = PriorityQueue.DeleteMin If u is the goal Exit Else Foreach neighbor v of u If v "Unvisited" Mark v "Visited" pq.insert(v) Mark u "Examined" End procedure

Let us consider the below example.

We start from source "S" and search for goal "I" using given costs and Best First search. pq initially contains S We remove s from and process unvisited neighbors of S to pq. pq now contains {A, C, B} (C is put before B because C has lesser cost) We remove A from pq and process unvisited neighbors of A to pq. pq now contains {C, B, E, D} We remove C from pq and process unvisited neighbors of C to pq. pq now contains {B, H, E, D} We remove B from pq and process unvisited neighbors of B to pq. pq now contains {H, E, D, F, G} We remove H from pq. Since our goal "I" is a neighbor of H, we return.

Below is the implementation of the above idea:

## C++

`// C++ program to implement Best First Search using priority` `// queue` `#include <bits/stdc++.h>` `using` `namespace` `std;` `typedef` `pair<` `int` `, ` `int` `> pi;` `vector<vector<pi> > graph;` `// Function for adding edges to graph` `void` `addedge(` `int` `x, ` `int` `y, ` `int` `cost)` `{` ` ` `graph[x].push_back(make_pair(cost, y));` ` ` `graph[y].push_back(make_pair(cost, x));` `}` `// Function For Implementing Best First Search` `// Gives output path having lowest cost` `void` `best_first_search(` `int` `source, ` `int` `target, ` `int` `n)` `{` ` ` `vector<` `bool` `> visited(n, ` `false` `);` ` ` `// MIN HEAP priority queue` ` ` `priority_queue<pi, vector<pi>, greater<pi> > pq;` ` ` `// sorting in pq gets done by first value of pair` ` ` `pq.push(make_pair(0, source));` ` ` `visited = ` `true` `;` ` ` `while` `(!pq.empty()) {` ` ` `int` `x = pq.top().second;` ` ` `// Displaying the path having lowest cost` ` ` `cout << x << ` `" "` `;` ` ` `pq.pop();` ` ` `if` `(x == target)` ` ` `break` `;` ` ` `for` `(` `int` `i = 0; i < graph[x].size(); i++) {` ` ` `if` `(!visited[graph[x][i].second]) {` ` ` `visited[graph[x][i].second] = ` `true` `;` ` ` `pq.push(graph[x][i]);` ` ` `}` ` ` `}` ` ` `}` `}` `// Driver code to test above methods` `int` `main()` `{` ` ` `// No. of Nodes` ` ` `int` `v = 14;` ` ` `graph.resize(v);` ` ` `// The nodes shown in above example(by alphabets) are` ` ` `// implemented using integers addedge(x,y,cost);` ` ` `addedge(0, 1, 3);` ` ` `addedge(0, 2, 6);` ` ` `addedge(0, 3, 5);` ` ` `addedge(1, 4, 9);` ` ` `addedge(1, 5, 8);` ` ` `addedge(2, 6, 12);` ` ` `addedge(2, 7, 14);` ` ` `addedge(3, 8, 7);` ` ` `addedge(8, 9, 5);` ` ` `addedge(8, 10, 6);` ` ` `addedge(9, 11, 1);` ` ` `addedge(9, 12, 10);` ` ` `addedge(9, 13, 2);` ` ` `int` `source = 0;` ` ` `int` `target = 9;` ` ` `// Function call` ` ` `best_first_search(source, target, v);` ` ` `return` `0;` `}` |

*chevron_right*

*filter_none*

**Output**

0 1 3 2 8 9

**Analysis :**

- worst case time complexity for Best First Search is O(n * Log n) where n is number of nodes. In worst case, we may have to visit all nodes before we reach goal. Note that priority queue is implemented using Min(or Max) Heap, and insert and remove operations take O(log n) time.
- Performance of the algorithm depends on how well the cost or evaluation function is designed.

**Related Article:**

A* Search Algorithm

This article is contributed by **Shambhavi Singh**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
- Best meeting point in 2D binary array
- Applications of Depth First Search
- Breadth First Search or BFS for a Graph
- Depth First Search or DFS for a Graph
- Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
- Top 10 Interview Questions on Depth First Search (DFS)
- Implementing Water Supply Problem using Breadth First Search
- Breadth First Search without using Queue
- Interpolation search vs Binary search
- Why is Binary Search preferred over Ternary Search?
- Sublist Search (Search a linked list in another list)
- Linear Search vs Binary Search
- Repeatedly search an element by doubling it after every successful search
- Meta Binary Search | One-Sided Binary Search
- Find the maximum element in an array which is first increasing and then decreasing
- Find the first repeating element in an array of integers
- Applications of Breadth First Traversal
- Iterative Depth First Traversal of Graph
- Find the first, second and third minimum elements in an array