You are on page 1of 11

DAV INSTITUTE OF ENGINEERING & TECHNOLOGY JALANDHAR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Artificial Intelligence

SUBMITTED TO: SUBMITTED BY:


Dr. Parveen Kakkar Karan Gupta
166/18
CSE 6th SEM

Write program to implement Breadth first search Traversal


#include <iostream>
#include <list>

using namespace std;

class Graph
{
int numVertices;
list<int>* adjLists;
bool* visited;
public:
Graph(int vertices);
void addEdge(int src, int dest);
void BFS(int startVertex);
};

Graph::Graph(int vertices)
{
numVertices = vertices;
adjLists = new list<int>[vertices];
}
void Graph::addEdge(int src, int dest)
{
adjLists[src].push_back(dest);
adjLists[dest].push_back(src);
}
void Graph::BFS(int startVertex)
{
visited = new bool[numVertices];
for (int i = 0; i < numVertices; i++)
visited[i] = false;
list<int> queue;
visited[startVertex] = true;
queue.push_back(startVertex);
list<int>::iterator i;
while (!queue.empty())

{
int currVertex = queue.front();
cout << "Visited " << currVertex << " ";
queue.pop_front();
for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); +
+i)
{
int adjVertex = *i;
if (!visited[adjVertex])
{
visited[adjVertex] = true;
queue.push_back(adjVertex);
}
}
}
}

int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

g.BFS(2);

return 0;
}

Output:-

Write program to implement Depth first search Traversal


#include <bits/stdc++.h>
using namespace std;
class Graph
{
public:
    map<int, bool> visited;
    map<int, list<int>> adj;
    void addEdge(int v, int w);
    void DFS(int v);
};
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}
void Graph::DFS(int v)
{
    visited[v] = true;
    cout << v << " ";
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFS(*i);
}
int main()
{
    Graph g;
    g.addEdge(0, 1);
    g.addEdge(0, 9);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(9, 3);
    cout << "Following is Depth First Traversal"
            " (starting from vertex 2) \n";
    g.DFS(2);
    return 0;
}

Output:-

Write program to implement A* search


#include "math.h"
#include <array>
#include <chrono>
#include <cstring>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <tuple>
using namespace std;
 
typedef pair<int, int> Pair;
typedef tuple<double, int, int> Tuple;
struct cell {
    // Row and Column index of its parent
    Pair parent;
    // f = g + h
    double f, g, h;
    cell()
        : parent(-1, -1)
        , f(-1)
        , g(-1)
        , h(-1)
    {
    }
};
template <size_t ROW, size_t COL>
bool isValid(const array<array<int, COL>, ROW>& grid,
             const Pair& point)
{
    if (ROW > 0 && COL > 0)
        return (point.first >= 0) && (point.first < ROW)
               && (point.second >= 0)
               && (point.second < COL);
 
    return false;
}
 template <size_t ROW, size_t COL>
bool isUnBlocked(const array<array<int, COL>, ROW>& grid,
                 const Pair& point)
{
    return isValid(grid, point)
           && grid[point.first][point.second] == 1;
}
 
bool isDestination(const Pair& position, const Pair& dest)
{
    return position == dest;
}
double calculateHValue(const Pair& src, const Pair& dest)
{
    // h is estimated with the two points distance formula
    return sqrt(pow((src.first - dest.first), 2.0)
                + pow((src.second - dest.second), 2.0));
}

template <size_t ROW, size_t COL>


void tracePath(
    const array<array<cell, COL>, ROW>& cellDetails,
    const Pair& dest)
{
    printf("\nThe Path is ");
 
    stack<Pair> Path;
 
    int row = dest.second;
    int col = dest.second;
    Pair next_node = cellDetails[row][col].parent;
    do {
        Path.push(next_node);
        next_node = cellDetails[row][col].parent;
        row = next_node.first;
        col = next_node.second;
    } while (cellDetails[row][col].parent != next_node);
 
    Path.emplace(row, col);
    while (!Path.empty()) {
        Pair p = Path.top();
        Path.pop();
        printf("-> (%d,%d) ", p.first, p.second);
    }
}
template <size_t ROW, size_t COL>
void aStarSearch(const array<array<int, COL>, ROW>& grid,
                 const Pair& src, const Pair& dest)
{
    if (!isValid(grid, src)) {
        printf("Source is invalid\n");
        return;
    }
    if (!isValid(grid, dest)) {
        printf("Destination is invalid\n");
        return;
    }
    if (!isUnBlocked(grid, src)
        || !isUnBlocked(grid, dest)) {
        printf("Source or the destination is blocked\n");
        return;
    }
    if (isDestination(src, dest)) {
        printf("We are already at the destination\n");
        return;
    }
    bool closedList[ROW][COL];
    memset(closedList, false, sizeof(closedList));
    array<array<cell, COL>, ROW> cellDetails;
    int i, j;
    i = src.first, j = src.second;
    cellDetails[i][j].f = 0.0;
    cellDetails[i][j].g = 0.0;
    cellDetails[i][j].h = 0.0;
    cellDetails[i][j].parent = { i, j };
 
    std::priority_queue<Tuple, std::vector<Tuple>,
                        std::greater<Tuple> >
        openList;
    openList.emplace(0.0, i, j);
    while (!openList.empty()) {
        const Tuple& p = openList.top();
        // Add this vertex to the closed list
        i = get<1>(p); // second element of tupla
        j = get<2>(p); // third element of tupla
 
        // Remove this vertex from the open list
        openList.pop();
        closedList[i][j] = true;
        
        for (int add_x = -1; add_x <= 1; add_x++) {
            for (int add_y = -1; add_y <= 1; add_y++) {
                Pair neighbour(i + add_x, j + add_y);
                // Only process this cell if this is a valid
                // one
                if (isValid(grid, neighbour)) {
                    // If the destination cell is the same
                    // as the current successor
                    if (isDestination(
                            neighbour,
                            dest)) { // Set the Parent of
                                     // the destination cell
                        cellDetails[neighbour.first]
                                   [neighbour.second]
                                       .parent
                            = { i, j };
                        printf("The destination cell is "
                               "found\n");
                        tracePath(cellDetails, dest);
                        return;
                    }
                    else if (!closedList[neighbour.first]
                                        [neighbour.second]
                             && isUnBlocked(grid,
                                            neighbour)) {
                        double gNew, hNew, fNew;
                        gNew = cellDetails[i][j].g + 1.0;
                        hNew = calculateHValue(neighbour,
                                               dest);
                        fNew = gNew + hNew;
 
                        if (cellDetails[neighbour.first]
                                       [neighbour.second]
                                           .f
                                == -1
                            || cellDetails[neighbour.first]
                                          [neighbour.second]
                                              .f
                                   > fNew) {
                            openList.emplace(
                                fNew, neighbour.first,
                                neighbour.second);
                             cellDetails[neighbour.first]
                                       [neighbour.second]
                                           .g
                                = gNew;
                            cellDetails[neighbour.first]
                                       [neighbour.second]
                                           .h
                                = hNew;
                            cellDetails[neighbour.first]
                                       [neighbour.second]
                                           .f
                                = fNew;
                            cellDetails[neighbour.first]
                                       [neighbour.second]
                                           .parent
                                = { i, j };
                        }
                    }
                }
            }
        }
    }
 
    printf("Failed to find the Destination Cell\n");
}
int main()
{
    array<array<int, 10>, 9> grid{
        { { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } },
          { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 } },
          { { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 } },
          { { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 } },
          { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 } },
          { { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 } },
          { { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 } },
          { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } },
          { { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } } }
    };
 
    // Source is the left-most bottom-most corner
    Pair src(8, 0);
 
    // Destination is the left-most top-most corner
    Pair dest(0, 0);
 
    aStarSearch(grid, src, dest);
 
    return 0;
}

Ques 4 :- Write program to implement water jug problem.


#include<bits/stdc++.h>
using namespace std;
int x;
int y;
void show(int a, int b);
int min(int w, int z)
{
if (w < z)
return w;
else
return z;
}
void show(int a, int b)
{
cout << setw(12) << a << setw(12) << b<<endl;
}
void s(int n)
{
int xq = 0, yq = 0;
int t;
cout << setw(15) <<"FIRST JUG"<< setw(15) <<"SECOND JUG"<<endl;
while (xq != n && yq!=n )
{
if (xq == 0)
{
xq = x;
show(xq, yq);
}
else if (yq == y)
{
yq = 0;
show(xq, yq);
}
else
{
t = min(y - yq, xq);
yq= yq + t;
xq = xq - t;
show(xq, yq);
}
}
}
int main()
{
int n;
cout << "Enter the liters of water required out of the two jugs: ";
cin >> n;
cout << "Enter the capacity of the first jug: ";
cin >> x;
cout << "Enter the capacity of the second jug: ";
cin >> y;
if(n<x || n<y)
{ if(n%(__gcd(x,y))==0)
s(n);
else
cout<<"This is not possible....\n";
}
else
cout<<"This is not possible....\n";
}

Output:-

You might also like