Uploaded by Aleeza gondal

Codes of AI

advertisement
Codes of AI
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
typedef pair<int, int> pi;
// Graph represented as an adjacency listvector<vector<pi>> graph;
// Function to add edges to the 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));}
// Best First Search function
void bestFirstSearch(int start, int goal, int n)
{ vector<bool> visited(n, false);
priority_queue<pi, vector<pi>, greater<pi>> pq;
pq.push(make_pair(0, start));
visited[start] = true;
while (!pq.empty())
{
int current = pq.top().second;
cout << current << " ";
pq.pop();
if (current == goal) {
break;
}
for (auto neighbor : graph[current])
{
int cost = neighbor.first;
int next = neighbor.second;
if (!visited[next])
{
visited[next] = true;
pq.push(make_pair(cost, next));
}
} }
}int main()
{ int nodes = 14;
graph.resize(nodes);
// Adding edges to the graph 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);
Download