0% found this document useful (0 votes)
3 views

AI Programming List

The document outlines various programming tasks related to Artificial Intelligence, including implementations of algorithms such as Depth-First Search, Towers of Hanoi, and Tic-Tac-Toe using C++ and Prolog. It discusses the goals, advantages, and disadvantages of AI, along with its applications in fields like gaming, natural language processing, and robotics. Additionally, it provides practical programming exercises and algorithms for solving specific AI-related problems.

Uploaded by

anuragpathak2233
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

AI Programming List

The document outlines various programming tasks related to Artificial Intelligence, including implementations of algorithms such as Depth-First Search, Towers of Hanoi, and Tic-Tac-Toe using C++ and Prolog. It discusses the goals, advantages, and disadvantages of AI, along with its applications in fields like gaming, natural language processing, and robotics. Additionally, it provides practical programming exercises and algorithms for solving specific AI-related problems.

Uploaded by

anuragpathak2233
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

AI programming List

AIML LAB AL 306


C++ Programming
1. Introduction of Artificial Intelligence and its application.
2. Implementation of Depth-First Search(DFS).
3. Write a program to implement towers of Hanoi
4. Write a program to implement water jug problem.
5. Write a program to implement Tic-Tac-Toe game problem.
6. Write a program to implement Production System.

7. Write a program to implement BFS (for 8 puzzle problem or Water Jug


problem or any AI search problem)

8. Write a program to implement DFS (for 8 puzzle problem or Water Jug


problem or any AI search problem).

9.
10. Write a program to solve N-Queens problem.
11. Write a program to Implement A* Algorithm.
12. Write a program to implement Single Player Game (Using any Heuristic
Function)
13. Write a program to solve 8 puzzle problem.
14. Write a program to solve travelling salesman problem

Prolog programming:
15.Assume given a set of facts of the form father(name1,name2) (name1 is the
father of name2).

16.Define a predicate brother(X,Y) which holds iff X and Y are brothers.


Define a predicate cousin(X,Y) which holds iff X and Y are cousins.

Define a predicate grandson(X,Y) which holds iff X is a grandson of Y.

Define a predicate descendent(X,Y) which holds iff X is a descendent of Y.

Consider the following genealogical tree: father(a,b). father(a,c). father(b,d).


father(b,e). father(c,f).

Say which answers, and in which order, are generated by your definitions for
the following queries in Prolog: ?- brother(X,Y). ?- cousin(X,Y). ?-
grandson(X,Y). ?- descendent(X,Y).
PRACTICAL NO.1
AIM: -Introduction of Artificial Intelligence and its application.

1.1 Artificial Intelligence


According to the father of Artificial Intelligence, John McCarthy, it is “The science and
engineering of making intelligent machines, especially intelligent computer programs”.
Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a
software think intelligently, in the similar manner the intelligent humans think.
AI is accomplished by studying how human brain thinks, and how humans learn, decide, and
work while trying to solve a problem, and then using the outcomes of this study as a basis of
developing intelligent software and systems.

1.2 Goals of AI
 To Create Expert Systems − The systems which exhibit intelligent behavior, learn,
demonstrate, explain, and advice its users.
 To Implement Human Intelligence in Machines − Creating systems that understand, think,
learn, and behave like humans.
1.3 Advantages of Artificial Intelligence
o More powerful are more useful computers
o New and improved interfaces
o Solving new problems
o Better handling of information
o Relieves information overload
o Conversion of information into knowledge
1.4 Disadvantages of Artificial Intelligence
o Increased costs
o Difficulty with software development-slow and expensive
o Few experienced programmers
o Few practical products have reached the market as yet
1.5 Foundation of AI: -

Fig.1.1
1.6 Applications of AI: -
AI has been dominant in various fields such as −
 Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc.,
where machine can think of large number of possible positions based on heuristic
knowledge.
 Natural Language Processing − It is possible to interact with the computer that
understands natural language spoken by humans.
 Expert Systems − There are some applications which integrate machine, software, and
special information to impart reasoning and advising. They provide explanation and advice
to the users.
 Vision Systems − These systems understand, interpret, and comprehend visual input on
the computer. For example,
o A spying aeroplane takes photographs, which are used to figure out spatial information
or map of the areas.
o Doctors use clinical expert system to diagnose the patient.
o Police use computer software that can recognize the face of criminal with the stored
portrait made by forensic artist.
 Speech Recognition − Some intelligent systems are capable of hearing and comprehending
the language in terms of sentences and their meanings while a human talks to it. It can
handle different accents, slang words, noise in the background, change in human’s noise
due to cold, etc.
 Handwriting Recognition − The handwriting recognition software reads the text written on
paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and
convert it into editable text.
 Intelligent Robots − Robots are able to perform the tasks given by a human. They have
sensors to detect physical data from the real world such as light, heat, temperature,
movement, sound, bump, and pressure. They have efficient processors, multiple sensors
and huge memory, to exhibit intelligence. In addition, they are capable of learning from
their mistakes and they can adapt to the new environment.
PRACTICAL NO.2
AIM: -Implementation of Depth-First Search(DFS).

2.1 Depth-First Search


DFS is also an important type of uniform search. DFS visits all the vertices in the graph. This
type of algorithm always chooses to go deeper into the graph. After DFS visited all the
reachable vertices from a particular sources vertices it chooses one of the remaining
undiscovered vertices and continues the search. DFS reminds the space limitation of breath
first search by always generating next a child of the deepest unexpanded nodded. The data
structure stack or (LIFO) is used for DFS. One interesting property of DFS is that, the
discover and finish time of each vertex from a parenthesis structure. If we use one open
parenthesis when a vertex is finished then the result is properly nested set of parenthesis.
2.2 Advantages of Depth-First Search
o DFS consumes very less memory space.
o It will reach at the goal node in a less time period than BFS if it traverses in a right path.
o It may find a solution without examining much of search because we may get the
desired solution in the very first go.
o t takes less memory as compared to BFS as BFS requires entire tree to be stored but
this requires only one path.
o Sometimes solution lies in earlier stages then DFS is better.
o If there are multiple solutions then DFS stops when first solution is found. Where as BFS
gives all the solutions at the same time.
2.3 Disadvantages of Depth-First Search
o There is a possibility that it may go down the left-most path forever. Even a finite graph
can generate an infinite tree.
o It is possible that may states keep reoccurring. There is no guarantee of finding the
goal node.
o Sometimes the states may also enter into infinite loops.
o Depth-First Search is not guaranteed to find the solution.
o And there is no guarantee to find a minimal solution, if more than one solution exists.
2.4 Algorithm of Depth-First Search
1: PUSH the starting node into the stack.
2: If the stack is empty then stop and return failure.
3: If the top node of the stack is the goal node, then stop and return success.
4: Else POP the top node from the stack and process it. Find all its neighbours that are in
ready state and PUSH them into the stack in any order.
5: Go to step 3.
6: Exit.

2.5 Program: -
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
void main()

{
int m;
clrscr();
cout<<"Enter of vertices";
cin>>n;
cout<<"Enter of edges";
cin>>m;
cout<<"EDGES\n";
for(k=1;k<=m;k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"Enter initial vertex";
cin>>v;
cout<<"Order of Visited vertices\n";
cout<<v<<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0&& visited[j]!=1&& visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;}
v=stk[--top];
cout<<v<<" ";
k++;
visit[v]=0;
visited[v]=1;
}
getch();
}

Output:-

Fig. 2.1
PRACTICAL NO. 3
AIM: -Write a program to implement towers of Hanoi

3.1 Tower of Hanoi


The solution to the Towers of Hanoi puzzle is a classic example of recursion. The ancient
puzzle of the Towers of Hanoi consists of a number of wooden disks mounted on three poles,
which are in turn attached to a baseboard. The disks each have different diameters and a hole
in the middle large enough for the poles to pass through. In the beginning, all the disks are on
the left pole.
The object of the puzzle is to move all the disks over to the right pole, one at a time, so that
they end up in the original order on that pole. You can use the middle pole as a temporary
resting place for disks, but at no time is a larger disk to be on top of a smaller one. It's easy to
solve the Towers of Hanoi with two or three disks, but the process becomes more difficult
with four or more disks.
3.2 Algorithm of Tower of Hanoi
1) If we have only one disk , then it can easily be moved from source to destination peg.
2) If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
3) To move n disks from source to destination, The steps to follow are -
• Step 1 − Move n-1 disks from source to aux
th
• Step 2 − Move n disk from source to dest
• Step 3 − Move n-1 disks from aux to dest
3.3 Program: -
#include
<iostream.h>
#include <conio.h>
void tower(int a,char from,char aux,char to){
if(a==1){
cout<<"\t\tMove disc 1 from "<<from<<" to "<<to<<"\n";
return;
} else{
tower(a-1,from,to,aux);
cout<<"\t\tMove disc "<<a<<" from "<<from<<" to "<<to<<"\n";
tower(a-1,aux,from,to); } }
void main(){
clrscr(); int n;
cout<<"\n\t\t*****Tower of Hanoi*****\n";
cout<<"\t\tEnter number of discs : ";
cin>>n; cout<<"\n\n";
tower(n,'A','B','C');
getch(); }
Output:-

Fig.3.1
PRACTICAL NO. 4
AIM: -Write a program to implement water jug problem.

4.1 Water jug problem


Statement :We are given 2 jugs, a 4 liter one and a 3- liter one. Neither has any measuring
markers on it. There is a pump that can be used to fill the jugs with water. How can we get
exactly 2 liters of water in to the 4-liter jugs?
Solution:-
The state space for this problem can be defined as
{ ( i ,j ) i = 0,1,2,3,4 j = 0,1,2,3}

‘i’ represents the number of liters of water in the 4-liter jug and ‘j’ represents the number of
liters of water in the 3-liter jug. The initial state is ( 0,0) that is no water on each jug. The
goal state is to get ( 2,n) for any value of ‘n’.
To solve this we have to make some assumptions not mentioned in the problem. They are
1. We can fill a jug from the pump.
2. We can pour water out of a jug to the ground.
3. We can pour water from one jug to another.
4. There is no measuring device available.

Table No. 4.1

4.2 Program: -
#include<iostream.h>
#include<iomanip.h>
#include<math.h>
#include<conio.h>
int xcapacity;
int ycapacity;
void display(int a, int b,int s);
int min(int d, int f)
{if (d < f)
return d;
else
return f;
} int steps(int n)
{
int x = 0, y = 0, step = 0;
int temp;
cout << setw(55) << “ Vessel A Vessel B Steps” << endl; while
(x != n )
{if (x == 0)
{ x = xcapacity;
step += 1;
cout << “Fill X “; display(x, y,step);
} else if (y ==
ycapacity) { y = 0;
step++;
cout << “Empty Y “; display(x, y,step);
}else {
temp = min(ycapacity – y, x);
y = y + temp;
x = x – temp;
step++;
cout << “Pour X in Y”; display(x, y, step);
}}
return step;
}void display(int a, int b,int s)
{cout << setw(16) << a << setw(15) << b << setw(15)<<s<<endl;
} void main()
{
int n, ans;
clrscr();

cout << “Enter the liters(GOAL) of water required to be filled in Vessel


1:”; cin >> n;
cout << “Enter the capacity of the vessel:
“; cin >> xcapacity;
cout << “Enter the capacity of the second 7essel: “;
cin >> ycapacity;
ans = steps(n);
cout << “Steps Required: “ <<
ans; cout<<”pause”;
}

Output:-

Fig.4.1
PRACTICAL NO. 5
(Method 1)
AIM: -Write a program to implement tic tac toe game for 0 and X.

5.1 Tic Tac Toe


Tic Tac Toe is a child's game played on a 3 by 3 grid. One player, X, starts by placing
an X at an unoccupied grid position. Then the other player, O, places an O at an
unoccupied grid position. Play alternates between X and O until the grid is filled or one
player's symbols occupy an entire line (vertical, horizontal, or diagonal) in the grid.
A tic-tac-toe AI program that never loses. This program uses the minimax algorithm
with alpha-beta pruning to reduce the search space.
1. return a value if a terminal state is found (+10, 0, -10)
2. go through available spots on the board
3. call the minimax function on each available spot (recursion)
4. evaluate returning values from function calls
5. and return the best value
5.2 Minimax Algorithm Visualizations:
The entire algorithm has been divided into five parts. We are assuming that the
player is playing X and the computer is playing O.
A. Check for winning condition.
B. Playing Defensive.
C. The First Move.
D. The Next Move.
E. Some Special Moves.

Fig.5.1

5.3 Program: -
#include<stdio.
h>
#include<conio
.h>
#include<stdlib
.h>
#include<iostre
am.h>
char matrix[3][3]; //intitial matrix
declaration char check(void); //
declaration of functions void
init_matrix(void);
void
get_player_move(void);
void
get_computer_move(void
); void disp_matrix(void);
int main(void)
{
clrscr();
char done;
cout<<"Human vs. AI Tic Tac Toe."<<endl;
cout<<"You will be playing against the
computer as 'X'"<<endl; done = ' ';
init_ma
trix();
do {
disp_m
atrix();
get_player_move();
done = check(); /* check winner */
if(done!= ' ') break; /* if winner
found...*/ get_computer_move();
done = check(); /* check for winner again */
} while(done== ' '); if(done=='X')
cout<<"Human won! (but AI very dumb anyway)\n"; else
cout<<"AI so stupid still can win against you..."<<endl; disp_matrix();
/* show final positions */
return 0;
}
void init_matrix(void) //matrix intitialisation
{
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) matrix[i][j] = ' ';
}
void get_player_move(void) //call function for player input
{
int x, y;
cout<<"Enter X,Y coordinates for your move:
"; scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y]!= ' ')
{
cout<<"Invalid move, try
again.\n";
get_player_move();
}
else matrix[x][y] = 'X';
}
void get_computer_move(void) //AI move input
{
int i, j;
for(i=0; i<3; i++)
{
for(j=0;j<3; j++)
if(matrix[i][j]==' ')
break;
if(matrix[i][j]==' ') break;
}
if(i*j==9)
{
cout<<"dr
aw\n";
exit(0);
}
else
matrix[i][j] = 'O';
}
void disp_matrix(void) //matrix display
{
int t;
for(t=0; t<3; t++)
{printf(" %c | %c | %c ",matrix[t][0],
matrix[t][1], matrix
[t][2]); if(t!=2)
printf("\n---|---|---\n");
}printf("\n");}
char check(void) //used for identifying winner
{ int i;
for(i=0; i<3; i++) /* check rows */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return
matrix[i][0]; for(i=0; i<3; i++) /* check
columns */ if(matrix[0][i]==matrix[1][i]
&& matrix[0][i]==matrix[2][i]) return
matrix[0][i];
/* test diagonals */
if(matrix[0][0]==matrix[1][1] && matrix[1]
[1]==matrix[2][2]) return matrix[0][0];
if(matrix[0][2]==matrix[1]
[1] && matrix[1]
[1]==matrix[2][0]) return
matrix[0][2];
return ' ';
}
Output:

Fig. 5.2

Method 2
Write a program to implement Tic-Tac-Toe game problem
#include <iostream>

#include <stdlib.h>

using namespace std;


//Array for the board

char board[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}};

//Variable Declaration

int choice;

int row,column;

char turn = 'X';

bool draw = false;

//Function to show the current status of the gaming board

void display_board(){

//Rander Game Board LAYOUT

cout<<"PLAYER - 1 [X]t PLAYER - 2 [O]nn";

cout<<"tt | | n";

cout<<"tt "<<board[0][0]<<" | "<<board[0][1]<<" | "<<board[0][2]<<" n";

cout<<"tt_____|_____|_____n";

cout<<"tt | | n";

cout<<"tt "<<board[1][0]<<" | "<<board[1][1]<<" | "<<board[1][2]<<" n";

cout<<"tt_____|_____|_____n";

cout<<"tt | | n";

cout<<"tt "<<board[2][0]<<" | "<<board[2][1]<<" | "<<board[2][2]<<" n";

cout<<"tt | | n";

//Function to get the player input and update the board

void player_turn(){

if(turn == 'X'){

cout<<"ntPlayer - 1 [X] turn : ";

}
else if(turn == 'O'){

cout<<"ntPlayer - 2 [O] turn : ";

//Taking input from user

//updating the board according to choice and reassigning the turn Start

cin>> choice;

//switch case to get which row and column will be update

switch(choice){

case 1: row=0; column=0; break;

case 2: row=0; column=1; break;

case 3: row=0; column=2; break;

case 4: row=1; column=0; break;

case 5: row=1; column=1; break;

case 6: row=1; column=2; break;

case 7: row=2; column=0; break;

case 8: row=2; column=1; break;

case 9: row=2; column=2; break;

default:

cout<<"Invalid Move";

if(turn == 'X' && board[row][column] != 'X' && board[row][column] != 'O'){

//updating the position for 'X' symbol if

//it is not already occupied

board[row][column] = 'X';

turn = 'O';

}else if(turn == 'O' && board[row][column] != 'X' && board[row][column] != 'O'){

//updating the position for 'O' symbol if


//it is not already occupied

board[row][column] = 'O';

turn = 'X';

}else {

//if input position already filled

cout<<"Box already filled!n Please choose another!!nn";

player_turn();

/* Ends */

display_board();

//Function to get the game status e.g. GAME WON, GAME DRAW GAME IN CONTINUE MODE

bool gameover(){

//checking the win for Simple Rows and Simple Column

for(int i=0; i<3; i++)

if(board[i][0] == board[i][1] && board[i][0] == board[i][2] || board[0][i] == board[1][i] && board[0]


[i] == board[2][i])

return false;

//checking the win for both diagonal

if(board[0][0] == board[1][1] && board[0][0] == board[2][2] || board[0][2] == board[1][1] &&


board[0][2] == board[2][0])

return false;

//Checking the game is in continue mode or not

for(int i=0; i<3; i++)

for(int j=0; j<3; j++)

if(board[i][j] != 'X' && board[i][j] != 'O')

return true;
//Checking the if game already draw

draw = true;

return false;

//Program Main Method

int main()

cout<<"tttT I C K -- T A C -- T O E -- G A M Ettt";

cout<<"nttttFOR 2 PLAYERSnttt";

while(gameover()){

display_board();

player_turn();

gameover();

if(turn == 'X' && draw == false){

cout<<"nnCongratulations!Player with 'X' has won the game";

else if(turn == 'O' && draw == false){

cout<<"nnCongratulations!Player with 'O' has won the game";

else

cout<<"nnGAME DRAW!!!nn";

PRACTICAL NO.6
AIM: -Write a program to implement production system.
6.1 Production System:
Search forms the core of many intelligent processes, it is useful to structure AI
programs in a way that facilitates describing and performing the search process.
Production system provides such structures .In other words the process of solving the
problem can usefully be modeled as production system.
The goal database is the central data structure used by an AI production system. The
production system. The production rules operate on the global database. Each rule has
a precondition that is either satisfied or not by the database. If the precondition is
satisfied, the rule can be applied. Application of the rule changes the database. The
control system chooses which applicable rule should be applied and ceases
computation when a termination condition on the database is satisfied. If several rules
are to fire at the same time, the control system resolves the conflicts.
6.2 Components of production system
o A set of rules of the form Ci → Ai where Ci is the condition part and Ai is the action
part. The condition determines when a given rule is applied, and the action
determines what happens when it is applied.
o One or more knowledge databases that contain whatever information is relevant
for the given problem. Some parts of the database may be permanent, while
others may temporary and only exist during the solution of the current problem. The
information in the databases may be structured in any appropriate manner.
o A control strategy that determines the order in which the rules are applied to the
database, and provides a way of resolving any conflicts that can arise when several
rules match at once.
o A rule applier which is the computational system that implements the control
strategy and applies the rules.
6.3 Four classes of production systems:-
1. A monotonic production system
2. A non monotonic production system
3. A partially commutative production system
4. A commutative production system.
6.4 Advantages of production systems:-
1. Production systems provide an excellent tool for structuring AI programs.
2. Production Systems are highly modular because the individual rules can be
added, removed or modified independently.
3. The production rules are expressed in a natural form, so the statements
contained in the knowledge base should the a recording of an expert thinking out
loud.
6.5 Disadvantages of Production Systems:-
1. One important disadvantage is the fact that it may be very difficult analyse the
flow of control within a production system because the individual rules don’t call
each other.
2. Production systems describe the operations that can be performed in a search for
a solution to the problem. They can be classified as follows.

6.6 Program
#include<iostr
eam.h>
#include<conio
.h> int main()
{
char
answe
r;
clrscr
();
cout<<"Answer the following question to determine whether JOHN should get
scholarship or not?"<<endl;
cout<<"Q1) Is John a Student?
(y/n)\n"; cin>>answer;
if(answer=='y'){
cout<<"John enjoys Student Life"<<endl;
cout<<"John Enjoys Student Life --> John Meets
Friends"<<endl; cout<<"John Enjoys Meets Friends -->
John Needs Money"<<endl; cout<<"Q2) Does John has a
job?(y/n)";
cin>>an
swer;
if(answ
er=='y')
{
cout<<"John Has Job --> John Has Free Time"<<endl;
cout<<"Since John Works in Free Time--> John Is Not Not Good In Studies
"<<endl; cout<<"John should not get the scholarship";
}
}
else
cout<<"John Will not recieve scholarship as he is not a
student"<<endl; return 0;
}

Output
PRACTICAL NO.7

AIM: Write a program to implement BFS Water Jug


problem

Water Jug problem

#include <cstdio>

#include <queue>

#include <stack>

#include <map>

#include <algorithm>

using namespace std;

// Representation of a state (x, y)

// x and y are the amounts of water in litres in the two jugs respectively

struct state {

int x, y;

// Used by map to efficiently implement lookup of seen states

bool operator < (const state& that) const {

if (x != that.x) return x < that.x;

return y < that.y;

};

// Capacities of the two jugs respectively and the target amount

int capacity_x, capacity_y, target;

void bfs(state start, stack <pair <state, int> >& path) {

queue <state> q;

state goal = (state) {-1, -1};


// Stores seen states so that they are not revisited and

// maintains their parent states for finding a path through

// the state space

// Mapping from a state to its parent state and rule no. that

// led to this state

map <state, pair <state, int> > parentOf;

q.push(start);

parentOf[start] = make_pair(start, 0);

while (!q.empty()) {

// Get the state at the front of the queue

state top = q.front();

q.pop();

// If the target state has been found, break

if (top.x == target || top.y == target) {

goal = top;

break;

// Find the successors of this state

// This step uses production rules to prune the search space

// Rule 1: (x, y) -> (capacity_x, y) if x < capacity_x

// Fill the first jug

if (top.x < capacity_x) {

state child = (state) {capacity_x, top.y};

// Consider this state for visiting only if it has not been visited before

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 1);


}

// Rule 2: (x, y) -> (x, capacity_y) if y < capacity_y

// Fill the second jug

if (top.y < capacity_y) {

state child = (state) {top.x, capacity_y};

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 2);

} // Rule 3: (x, y) -> (0, y) if x > 0

// Empty the first jug

if (top.x > 0) {

state child = (state) {0, top.y};

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 3);

} // Rule 4: (x, y) -> (x, 0) if y > 0 // Empty the second jug

if (top.y > 0) {

state child = (state) {top.x, 0};

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 4);

} // Rule 5: (x, y) -> (min(x + y, capacity_x), max(0, x + y - capacity_x)) if y > 0

// Pour water from the second jug into the first jug until the first jug is full
// or the second jug is empty

if (top.y > 0) {

state child = (state) {min(top.x + top.y, capacity_x), max(0, top.x + top.y - capacity_x)};

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 5);

} // Rule 6: (x, y) -> (max(0, x + y - capacity_y), min(x + y, capacity_y)) if x > 0

// Pour water from the first jug into the second jug until the second jug is full

// or the first jug is empty

if (top.x > 0) {

state child = (state) {max(0, top.x + top.y - capacity_y), min(top.x + top.y, capacity_y)};

if (parentOf.find(child) == parentOf.end()) {

q.push(child);

parentOf[child] = make_pair(top, 6);

} } }

// Target state was not found

if (goal.x == -1 || goal.y == -1)

return;

// backtrack to generate the path through the state space

path.push(make_pair(goal, 0));

// remember parentOf[start] = (start, 0)

while (parentOf[path.top().first].second != 0)

path.push(parentOf[path.top().first]);}

int main() {

stack <pair <state, int> > path;


printf("Enter the capacities of the two jugs : ");

scanf("%d %d", &capacity_x, &capacity_y);

printf("Enter the target amount : ");

scanf("%d", &target);

bfs((state) {0, 0}, path);

if (path.empty())

printf("\nTarget cannot be reached.\n");

else {

printf("\nNumber of moves to reach the target : %d\nOne path to the target is as follows :\n",
path.size() - 1);

while (!path.empty()) {

state top = path.top().first;

int rule = path.top().second;

path.pop();

switch (rule) {

case 0: printf("State : (%d, %d)\n#\n", top.x, top.y);

break;

case 1: printf("State : (%d, %d)\nAction : Fill the first jug\n", top.x, top.y);

break;

case 2: printf("State : (%d, %d)\nAction : Fill the second jug\n", top.x, top.y);

break;

case 3: printf("State : (%d, %d)\nAction : Empty the first jug\n", top.x, top.y);

break;

case 4: printf("State : (%d, %d)\nAction : Empty the second jug\n", top.x, top.y);

break;

case 5: printf("State : (%d, %d)\nAction : Pour from second jug into first jug\n", top.x,
top.y);
break;

case 6: printf("State : (%d, %d)\nAction : Pour from first jug into second jug\n", top.x,
top.y);

break;

} } } return 0; }
PRACTICAL NO.8

AIM: Write a program to implement DFS Water Jug problem or any


AI search problem)
#include <cstdio>

#include <stack>

#include <map>

#include <algorithm>

using namespace std;

// Representation of a state (x, y)

// x and y are the amounts of water in litres in the two jugs respectively

struct state {

int x, y;

// Used by map to efficiently implement lookup of seen states

bool operator < (const state& that) const {

if (x != that.x) return x < that.x;

return y < that.y;

} };

// Capacities of the two jugs respectively and the target amount

int capacity_x, capacity_y, target;

void dfs(state start, stack <pair <state, int> >& path) {

stack <state> s;

state goal = (state) {-1, -1};

// Stores seen states so that they are not revisited and

// maintains their parent states for finding a path through

// the state space

// Mapping from a state to its parent state and rule no. that
// led to this state

map <state, pair <state, int> > parentOf;

s.push(start);

parentOf[start] = make_pair(start, 0);

while (!s.empty()) {

// Get the state at the front of the stack

state top = s.top();

s.pop();

// If the target state has been found, break

if (top.x == target || top.y == target) {

goal = top;

break; }

// Find the successors of this state

// This step uses production rules to produce successors of the current state

// while pruning away branches which have been seen before

// Rule 1: (x, y) -> (capacity_x, y) if x < capacity_x

// Fill the first jug

if (top.x < capacity_x) {

state child = (state) {capacity_x, top.y};

// Consider this state for visiting only if it has not been visited before

if (parentOf.find(child) == parentOf.end()) {

s.push(child);

parentOf[child] = make_pair(top, 1); } }

// Rule 2: (x, y) -> (x, capacity_y) if y < capacity_y

// Fill the second jug

if (top.y < capacity_y) {


state child = (state) {top.x, capacity_y};

if (parentOf.find(child) == parentOf.end()) {

s.push(child);

parentOf[child] = make_pair(top, 2); } }

// Rule 3: (x, y) -> (0, y) if x > 0

// Empty the first jug

if (top.x > 0) {

state child = (state) {0, top.y};

if (parentOf.find(child) == parentOf.end()) {

s.push(child);

parentOf[child] = make_pair(top, 3); } }

// Rule 4: (x, y) -> (x, 0) if y > 0

// Empty the second jug

if (top.y > 0) {

state child = (state) {top.x, 0};

if (parentOf.find(child) == parentOf.end()) {

s.push(child);

parentOf[child] = make_pair(top, 4); } }

// Rule 5: (x, y) -> (min(x + y, capacity_x), max(0, x + y - capacity_x)) if y > 0

// Pour water from the second jug into the first jug until the first jug is full

// or the second jug is empty

if (top.y > 0) {

state child = (state) {min(top.x + top.y, capacity_x), max(0, top.x + top.y - capacity_x)};

if (parentOf.find(child) == parentOf.end()) {
s.push(child);

parentOf[child] = make_pair(top, 5); } }

// Rule 6: (x, y) -> (max(0, x + y - capacity_y), min(x + y, capacity_y)) if x > 0

// Pour water from the first jug into the second jug until the second jug is full

// or the first jug is empty

if (top.x > 0) {

state child = (state) {max(0, top.x + top.y - capacity_y), min(top.x + top.y, capacity_y)};

if (parentOf.find(child) == parentOf.end()) {

s.push(child);

parentOf[child] = make_pair(top, 6); } } }

// Target state was not found

if (goal.x == -1 || goal.y == -1)

return;

// backtrack to generate the path through the state space

path.push(make_pair(goal, 0));

// remember parentOf[start] = (start, 0)

while (parentOf[path.top().first].second != 0)

path.push(parentOf[path.top().first]);}

int main() {

stack <pair <state, int> > path;

printf("Enter the capacities of the two jugs : ");

scanf("%d %d", &capacity_x, &capacity_y);

printf("Enter the target amount : ");

scanf("%d", &target);

dfs((state) {0, 0}, path);


if (path.empty())

printf("\nTarget cannot be reached.\n");

else {

printf("\nNumber of moves to reach the target : %d\nOne path to the target is as follows :\n",
path.size() - 1);

while (!path.empty()) {

state top = path.top().first;

int rule = path.top().second;

path.pop();

switch (rule) {

case 0: printf("State : (%d, %d)\n#\n", top.x, top.y);

break;

case 1: printf("State : (%d, %d)\nAction : Fill the first jug\n", top.x, top.y);

break;

case 2: printf("State : (%d, %d)\nAction : Fill the second jug\n", top.x, top.y);

break;

case 3: printf("State : (%d, %d)\nAction : Empty the first jug\n", top.x, top.y);

break;

case 4: printf("State : (%d, %d)\nAction : Empty the second jug\n", top.x, top.y);

break;

case 5: printf("State : (%d, %d)\nAction : Pour from second jug into first jug\n", top.x,
top.y);

break;

case 6: printf("State : (%d, %d)\nAction : Pour from first jug into second jug\n", top.x,
top.y);

break; } } } return 0;}


PRACTICAL NO.9

Aim: Write a program to solve N-Queens problem

#define N 4#include <stdbool.h>

#include <stdio.h>

void printSolution(int board[N][N]) {

for (int i = 0; i < N; i++) {

for (int j = 0; j < N; j++)

printf(" %d ", board[i][j]);

printf("\n"); }}

bool isSafe(int board[N][N], int row, int col) {

int i, j;

/* Check this row on left side */

for (i = 0; i < col; i++)

if (board[row][i])

return false;

/* Check upper diagonal on left side */

for (i = row, j = col; i >= 0 && j >= 0; i--, j--)

if (board[i][j])

return false;

for (i = row, j = col; j >= 0 && i < N; i++, j--)

if (board[i][j])

return false;

return true;}

bool solveNQUtil(int board[N][N], int col) {


if (col >= N)

return true;

for (int i = 0; i < N; i++) {

if (isSafe(board, i, col)) {

board[i][col] = 1;

if (solveNQUtil(board, col + 1))

return true;

board[i][col] = 0; // BACKTRACK } }

return false;}

bool solveNQ() {

int board[N][N] = {

{ 0, 0, 0, 0 },

{ 0, 0, 0, 0 },

{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {

printf("Solution does not exist");

return false; }

printSolution(board);

return true;}

int main() {

solveNQ();

return 0;}

PRACTICAL NO.10

AIM: Write a program to Implement A* Algorithm.


#include<bits/stdc++.h>

using namespace std;

#define ROW 9
#define COL 10

typedef pair < int, int > Pair;

typedef pair < double, pair < int, int >> pPair;

struct cell {

int parent_i, parent_j;

double f, g, h;

};

bool isValid(int row, int col) {

return (row >= 0) && (row < ROW) &&

(col >= 0) && (col < COL);

bool isUnBlocked(int grid[][COL], int row, int col) {

if (grid[row][col] == 1)

return (true);

else

return (false);

bool isDestination(int row, int col, Pair dest) {

if (row == dest.first && col == dest.second)

return (true);

else

return (false);

double calculateHValue(int row, int col, Pair dest) {

return ((double) sqrt((row - dest.first) * (row - dest.first) +

(col - dest.second) * (col - dest.second)));

}
void tracePath(cell cellDetails[][COL], Pair dest) {

printf("\nThe Path is ");

int row = dest.first;

int col = dest.second;

stack < Pair > Path;

while (!(cellDetails[row][col].parent_i == row &&

cellDetails[row][col].parent_j == col)) {

Path.push(make_pair(row, col));

int temp_row = cellDetails[row][col].parent_i;

int temp_col = cellDetails[row][col].parent_j;

row = temp_row;

col = temp_col;

Path.push(make_pair(row, col));

while (!Path.empty()) {

pair < int, int > p = Path.top();

Path.pop();

printf("-> (%d,%d) ", p.first, p.second);

return;

void aStarSearch(int grid[][COL], Pair src, Pair dest) {

if (isValid(src.first, src.second) == false) {

printf("Source is invalid\n");

return;

if (isValid(dest.first, dest.second) == false) {


printf("Destination is invalid\n");

return;

if (isUnBlocked(grid, src.first, src.second) == false ||

isUnBlocked(grid, dest.first, dest.second) == false) {

printf("Source or the destination is blocked\n");

return;

if (isDestination(src.first, src.second, dest) == true) {

printf("We are already at the destination\n");

return;

bool closedList[ROW][COL];

memset(closedList, false, sizeof(closedList));

cell cellDetails[ROW][COL];

int i, j;

for (i = 0; i < ROW; i++) {

for (j = 0; j < COL; j++) {

cellDetails[i][j].f = FLT_MAX;

cellDetails[i][j].g = FLT_MAX;

cellDetails[i][j].h = FLT_MAX;

cellDetails[i][j].parent_i = -1;

cellDetails[i][j].parent_j = -1;

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 = i;

cellDetails[i][j].parent_j = j;

set < pPair > openList;

openList.insert(make_pair(0.0, make_pair(i, j)));

bool foundDest = false;

while (!openList.empty()) {

pPair p = * openList.begin();

openList.erase(openList.begin());

i = p.second.first;

j = p.second.second;

closedList[i][j] = true;

double gNew, hNew, fNew;

if (isValid(i - 1, j) == true) {

if (isDestination(i - 1, j, dest) == true) {

cellDetails[i - 1][j].parent_i = i;

cellDetails[i - 1][j].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i - 1][j] == false &&

isUnBlocked(grid, i - 1, j) == true) {

gNew = cellDetails[i][j].g + 1.0;

hNew = calculateHValue(i - 1, j, dest);

fNew = gNew + hNew;


if (cellDetails[i - 1][j].f == FLT_MAX ||

cellDetails[i - 1][j].f > fNew) {

openList.insert(make_pair(fNew,

make_pair(i - 1, j)));

cellDetails[i - 1][j].f = fNew;

cellDetails[i - 1][j].g = gNew;

cellDetails[i - 1][j].h = hNew;

cellDetails[i - 1][j].parent_i = i;

cellDetails[i - 1][j].parent_j = j;

//----------- 2nd Successor (South) ------------

if (isValid(i + 1, j) == true) {

// If the destination cell is the same as the

// current successor

if (isDestination(i + 1, j, dest) == true) {

// Set the Parent of the destination cell

cellDetails[i + 1][j].parent_i = i;

cellDetails[i + 1][j].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i + 1][j] == false &&

isUnBlocked(grid, i + 1, j) == true) {

gNew = cellDetails[i][j].g + 1.0;


hNew = calculateHValue(i + 1, j, dest);

fNew = gNew + hNew;

if (cellDetails[i + 1][j].f == FLT_MAX ||

cellDetails[i + 1][j].f > fNew) {

openList.insert(make_pair(fNew, make_pair(i + 1, j)));

cellDetails[i + 1][j].f = fNew;

cellDetails[i + 1][j].g = gNew;

cellDetails[i + 1][j].h = hNew;

cellDetails[i + 1][j].parent_i = i;

cellDetails[i + 1][j].parent_j = j;

//----------- 3rd Successor (East) ------------

if (isValid(i, j + 1) == true) {

if (isDestination(i, j + 1, dest) == true) {

cellDetails[i][j + 1].parent_i = i;

cellDetails[i][j + 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i][j + 1] == false &&

isUnBlocked(grid, i, j + 1) == true) {

gNew = cellDetails[i][j].g + 1.0;

hNew = calculateHValue(i, j + 1, dest);

fNew = gNew + hNew;


if (cellDetails[i][j + 1].f == FLT_MAX ||

cellDetails[i][j + 1].f > fNew) {

openList.insert(make_pair(fNew,

make_pair(i, j + 1)));

cellDetails[i][j + 1].f = fNew;

cellDetails[i][j + 1].g = gNew;

cellDetails[i][j + 1].h = hNew;

cellDetails[i][j + 1].parent_i = i;

cellDetails[i][j + 1].parent_j = j;

//----------- 4th Successor (West) ------------

if (isValid(i, j - 1) == true) {

if (isDestination(i, j - 1, dest) == true) {

cellDetails[i][j - 1].parent_i = i;

cellDetails[i][j - 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i][j - 1] == false &&

isUnBlocked(grid, i, j - 1) == true) {

gNew = cellDetails[i][j].g + 1.0;

hNew = calculateHValue(i, j - 1, dest);

fNew = gNew + hNew;

if (cellDetails[i][j - 1].f == FLT_MAX ||


cellDetails[i][j - 1].f > fNew) {

openList.insert(make_pair(fNew,

make_pair(i, j - 1)));

// Update the details of this cell

cellDetails[i][j - 1].f = fNew;

cellDetails[i][j - 1].g = gNew;

cellDetails[i][j - 1].h = hNew;

cellDetails[i][j - 1].parent_i = i;

cellDetails[i][j - 1].parent_j = j;

//----------- 5th Successor (North-East) ------------

if (isValid(i - 1, j + 1) == true) {

if (isDestination(i - 1, j + 1, dest) == true) {

cellDetails[i - 1][j + 1].parent_i = i;

cellDetails[i - 1][j + 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i - 1][j + 1] == false &&

isUnBlocked(grid, i - 1, j + 1) == true) {

gNew = cellDetails[i][j].g + 1.414;

hNew = calculateHValue(i - 1, j + 1, dest);

fNew = gNew + hNew;

if (cellDetails[i - 1][j + 1].f == FLT_MAX ||


cellDetails[i - 1][j + 1].f > fNew) {

openList.insert(make_pair(fNew,

make_pair(i - 1, j + 1)));

cellDetails[i - 1][j + 1].f = fNew;

cellDetails[i - 1][j + 1].g = gNew;

cellDetails[i - 1][j + 1].h = hNew;

cellDetails[i - 1][j + 1].parent_i = i;

cellDetails[i - 1][j + 1].parent_j = j;

//----------- 6th Successor (North-West) ------------

if (isValid(i - 1, j - 1) == true) {

if (isDestination(i - 1, j - 1, dest) == true) {

cellDetails[i - 1][j - 1].parent_i = i;

cellDetails[i - 1][j - 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i - 1][j - 1] == false &&

isUnBlocked(grid, i - 1, j - 1) == true) {

gNew = cellDetails[i][j].g + 1.414;

hNew = calculateHValue(i - 1, j - 1, dest);

fNew = gNew + hNew;

if (cellDetails[i - 1][j - 1].f == FLT_MAX ||

cellDetails[i - 1][j - 1].f > fNew) {


openList.insert(make_pair(fNew, make_pair(i - 1, j - 1)));

// Update the details of this cell

cellDetails[i - 1][j - 1].f = fNew;

cellDetails[i - 1][j - 1].g = gNew;

cellDetails[i - 1][j - 1].h = hNew;

cellDetails[i - 1][j - 1].parent_i = i;

cellDetails[i - 1][j - 1].parent_j = j;

//----------- 7th Successor (South-East) ------------

if (isValid(i + 1, j + 1) == true) {

if (isDestination(i + 1, j + 1, dest) == true) {

cellDetails[i + 1][j + 1].parent_i = i;

cellDetails[i + 1][j + 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i + 1][j + 1] == false &&

isUnBlocked(grid, i + 1, j + 1) == true) {

gNew = cellDetails[i][j].g + 1.414;

hNew = calculateHValue(i + 1, j + 1, dest);

fNew = gNew + hNew;

if(cellDetails[i + 1][j + 1].f == FLT_MAX ||

cellDetails[i + 1][j + 1].f > fNew) {


openList.insert(make_pair(fNew,

make_pair(i + 1, j + 1)));

cellDetails[i + 1][j + 1].f = fNew;

cellDetails[i + 1][j + 1].g = gNew;

cellDetails[i + 1][j + 1].h = hNew;

cellDetails[i + 1][j + 1].parent_i = i;

cellDetails[i + 1][j + 1].parent_j = j;

//----------- 8th Successor (South-West) ------------

if (isValid(i + 1, j - 1) == true) {

if (isDestination(i + 1, j - 1, dest) == true) {

// Set the Parent of the destination cell

cellDetails[i + 1][j - 1].parent_i = i;

cellDetails[i + 1][j - 1].parent_j = j;

printf("The destination cell is found\n");

tracePath(cellDetails, dest);

foundDest = true;

return;

} else if (closedList[i + 1][j - 1] == false &&

isUnBlocked(grid, i + 1, j - 1) == true) {

gNew = cellDetails[i][j].g + 1.414;

hNew = calculateHValue(i + 1, j - 1, dest);

fNew = gNew + hNew;

if (cellDetails[i + 1][j - 1].f == FLT_MAX ||

cellDetails[i + 1][j - 1].f > fNew) {


openList.insert(make_pair(fNew,

make_pair(i + 1, j - 1)));

cellDetails[i + 1][j - 1].f = fNew;

cellDetails[i + 1][j - 1].g = gNew;

cellDetails[i + 1][j - 1].h = hNew;

cellDetails[i + 1][j - 1].parent_i = i;

cellDetails[i + 1][j - 1].parent_j = j;

if (foundDest == false)

printf("Failed to find the Destination Cell\n");

return;

int main() {

/* Description of the Grid1--> The cell is not blocked

0--> The cell is blocked */

int grid[ROW][COL] =

{ 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 }

};

Pair src = make_pair(8, 0);

Pair dest = make_pair(0, 0);

aStarSearch(grid, src, dest);

return (0);

PRACTICAL NO.11

AIM: Write a program to implement Single Player


Game (Using any Heuristic Function)
#include <stdio.h>

#include <stdlib.h>

char matrix[3][3];

char check(void);

void init_matrix(void);

void get_player_move(void);

void get_computer_move(void);

void disp_matrix(void);

int main(void) {

char done;

printf("This is the game of Tic Tac Toe.\n");

printf("You will be playing against the computer.\n");

done = ' ';


init_matrix();

do {

disp_matrix();

get_player_move();

done = check(); /* see if winner */

if (done != ' ') break; /* winner!*/

get_computer_move();

done = check(); /* see if winner */

} while (done == ' ');

if (done == 'X') printf("You won!\n");

else printf("I won!!!!\n");

disp_matrix(); /* show final positions */

return 0;

/* Initialize the matrix. */

void init_matrix(void) {

int i, j;

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++) matrix[i][j] = ' ';

/* Get a player's move. */

void get_player_move(void) {

int x, y;

printf("Enter X,Y coordinates for your move: ");

scanf("%d%*c%d", & x, & y);


x--;

y--;

if (matrix[x][y] != ' ') {

printf("Invalid move, try again.\n");

get_player_move();

} else matrix[x][y] = 'X';

/* Get a move from the computer. */

void get_computer_move(void) {

int i, j;

for (i = 0; i < 3; i++) {

for (j = 0; j < 3; j++)

if (matrix[i][j] == ' ') break;

if (matrix[i][j] == ' ') break;

if (i * j == 9) {

printf("draw\n");

exit(0);

} else

matrix[i][j] = 'O';

/* Display the matrix on the screen. */


void disp_matrix(void) {

int t;

for (t = 0; t < 3; t++) {

printf(" %c | %c | %c ", matrix[t][0],

matrix[t][1], matrix[t][2]);

if (t != 2) printf("\n---|---|---\n");

printf("\n");

/* See if there is a winner. */

char check(void) {

int i;

for (i = 0; i < 3; i++) /* check rows */

if (matrix[i][0] == matrix[i][1] &&

matrix[i][0] == matrix[i][2]) return matrix[i][0];

for (i = 0; i < 3; i++) /* check columns */

if (matrix[0][i] == matrix[1][i] &&

matrix[0][i] == matrix[2][i]) return matrix[0][i];

/* test diagonals */

if (matrix[0][0] == matrix[1][1] &&

matrix[1][1] == matrix[2][2])

return matrix[0][0];

if (matrix[0][2] == matrix[1][1] &&

matrix[1][1] == matrix[2][0])
return matrix[0][2];

return ' ';

PRACTICAL NO.12

AIM: Write a program to solve 8 puzzle problem


#include <bits/stdc++.h>

using namespace std;

#define N 3

struct Node {

Node * parent;

int mat[N][N];

int x, y;

int cost;

int level;

};

int printMatrix(int mat[N][N]) {

for (int i = 0; i < N; i++) {

for (int j = 0; j < N; j++)

printf("%d ", mat[i][j]);

printf("\n");

Node * newNode(int mat[N][N], int x, int y, int newX,

int newY, int level, Node * parent) {

Node * node = new Node;

node -> parent = parent;


memcpy(node -> mat, mat, sizeof node -> mat);

swap(node -> mat[x][y], node -> mat[newX][newY]);

node -> cost = INT_MAX;

node -> level = level;

node -> x = newX;

node -> y = newY;

return node;

int row[] = { 1, 0, -1, 0 };

int col[] = { 0, -1, 0, 1 };

int calculateCost(int initial[N][N], int final[N][N]) {

int count = 0;

for (int i = 0; i < N; i++)

for (int j = 0; j < N; j++)

if (initial[i][j] && initial[i][j] != final[i][j])

count++;

return count;

int isSafe(int x, int y) {

return (x >= 0 && x < N && y >= 0 && y < N);

void printPath(Node * root) {

if (root == NULL)

return;

printPath(root -> parent);

printMatrix(root -> mat);

printf("\n");
}

struct comp {

bool operator()(const Node * lhs,

const Node * rhs) const {

return (lhs -> cost + lhs -> level) > (rhs -> cost + rhs -> level);

};

void solve(int initial[N][N], int x, int y,

int final[N][N]) {

priority_queue < Node * , std::vector < Node * > , comp > pq;

Node * root = newNode(initial, x, y, x, y, 0, NULL);

root -> cost = calculateCost(initial, final);

pq.push(root);

while (!pq.empty()) {

Node * min = pq.top();

pq.pop();

if (min -> cost == 0) {

printPath(min);

return;

for (int i = 0; i < 4; i++) {

if (isSafe(min -> x + row[i], min -> y + col[i])) {

Node * child = newNode(min -> mat, min -> x,

min -> y, min -> x + row[i],

min -> y + col[i],

min -> level + 1, min);

child -> cost = calculateCost(child -> mat, final);


pq.push(child);

int main() {

int initial[N][N] = {

{1, 2, 3},

{5, 6, 0},

{7, 8, 4}

};

int final[N][N] = {

{1, 2, 3},

{5, 8, 6},

{0, 7, 4}

};

int x = 1, y = 2;

solve(initial, x, y, final);

return 0;

}
PRACTICAL NO.13

AIM: Write a program to solve travelling salesman problem


#include<stdio.h>

int ary[10][10], completed[10], n, cost = 0;

void takeInput() {

int i, j;

printf("Enter the number of villages: ");

scanf("%d", & n);

printf("\nEnter the Cost Matrix\n");

for (i = 0; i < n; i++) {

printf("\nEnter Elements of Row: %d\n", i + 1);

for (j = 0; j < n; j++)

scanf("%d", & ary[i][j]);

completed[i] = 0;

printf("\n\nThe cost list is:");

for (i = 0; i < n; i++) {

printf("\n");

for (j = 0; j < n; j++)

printf("\t%d", ary[i][j]);

void mincost(int city) {

int i, ncity;

completed[city] = 1;

printf("%d--->", city + 1);


ncity = least(city);

if (ncity == 999) {

ncity = 0;

printf("%d", ncity + 1);

cost += ary[city][ncity];

return;

mincost(ncity);

int least(int c) {

int i, nc = 999;

int min = 999, kmin;

for (i = 0; i < n; i++) {

if ((ary[c][i] != 0) && (completed[i] == 0))

if (ary[c][i] + ary[i][c] < min) {

min = ary[i][0] + ary[c][i];

kmin = ary[c][i];

nc = i;

if (min != 999)

cost += kmin;

return nc;

int main() {

takeInput();

printf("\n\nThe Path is:\n");


mincost(0); //passing 0 because starting vertex

printf("\n\nMinimum cost is %d\n ", cost);

return 0;

https://gtupractical.com/artificial-intelligence-practical/

You might also like