0% found this document useful (0 votes)
18 views63 pages

Lab - File - AI

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views63 pages

Lab - File - AI

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

ARTIFICIAL INTELLIGENCE(CS3EA01/CB3CO14)

List of Experiment

1. Write a program to implement Breadth First Search


(BFS).
2. Write a program to implement Depth FirstSearch
(DFS).
3. Write a program to implement t i k tac toe.
4. Write a program to implement 8 puzzle problem.
5. Write a program to implement Water jug problem.
6. Write a program to implement Travelling salesmanproblem.
7. Write a program to implement tower of Hanoi.
8. Write a program to implement Banana monkeyproblem.
9. Write a program to implement N queue problem.
10. Write a program to implement Minimax and alphabeta
pruning algorithm.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
1
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-1

Experiment Title : Implement Breadth First Search Page 1 of 5


Algorithm.

Objective: Implement Breadth First Search


Algorithm.

Objective: Implement Breadth First Search.

Definition: The Breadth First Search (BFS) algorithm is used to search a graph data structure
for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at
the current depth level before moving on to the nodes at the next depth level.

Starting from the root, all the nodes at a particular level are visited first and then the
nodes of the next level are traversed till all the nodes are visited.

To do this a queue is used. All the adjacent unvisited nodes of the current level are pushed
into the queue and the nodes of the current level are marked visited and popped from the
queue.

Algorithm:

1. Start at the source node.

2. Create a queue (FIFO data structure) and enqueue the source node.

3. Mark the source node as visited.

4. While the queue is not empty:

a. Dequeue a node from the front of the queue.

b. Process the node (e.g., print it).

c. Enqueue all unvisited neighbors of the node.

d. Mark each neighbor as visited.

5. Repeat steps 4 until the queue is empty.

Advantages of BFS:

1 BFS will never get trapped exploring the useful path forever.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
2
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-1

Experiment Title : Implement Breadth First Search Page 2 of 5


Algorithm.

2 If there is a solution, BFS will definitely find it.

3 If there is more than one solution then BFS can find the minimal one that requires less
number of steps.

4 Low storage requirement – linear with depth.

5 Easily programmable

Disadvantages of BFS:

1 BFS consumes large memory space.

2 Its time complexity is more.

3 It has long pathways, when all paths to a destination are on approximately the same search
depth.

4 It can be very memory intensive since it needs to keep track of all the nodes in the search
tree.

5 It can be slow since it expands all the nodes at each level before moving on to the next
level.

Time Complexity of BFS: The time complexity of BFS is O(V + E), where V is the number
of vertices and E is the number of edges in the graph.

Space Complexity of BFS: The space complexity of BFS is O(V), where V is the number of
vertices.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
3
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-1

Experiment Title : Implement Breadth First Search Page 3of 5


Algorithm.

Code:

#include <iostream>

#include <list>

#include <queue>

#include <unordered_map>

class Graph {

std::unordered_map<int, std::list<int>> adjList;

public: void addEdge(int v, int w) {

adjList[v].push_back(w);

void bfs(int start) {

std::unordered_map<int, bool> visited;

for (const auto& pair : adjList) {

visited[pair.first] = false;

std::queue<int> queue;

queue.push(start);

visited[start] = true;

while (!queue.empty()) {

int vertex = queue.front();

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
4
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-1

Experiment Title : Implement Breadth First Search Page 4 of 5


Algorithm.

std::cout << vertex << " "

queue.pop();

for (int neighbor : adjList[vertex]) {

if (!visited[neighbor]) {

queue.push(neighbor);

visited[neighbor] = true;

} } } }};

int main() {

Graph g;

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

std::cout << "BFS starting from vertex 2:" << std::endl;

g.bfs(2);

return 0;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
5
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-1

Experiment Title : Implement Breadth First Search Page 5 of 5


Algorithm.

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
6
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-2

Experiment Title : Implement Depth First Search Page 1 of 5


Algorithm.

Objective: Implement Depth First Search Algorithm.

Defination: Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a
tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be
visited twice). To avoid processing a node more than once, use a boolean visited array. A
graph can have more than one DFS traversal.

Depth-First Search or DFS algorithm is a recursive algorithm that uses the backtracking
principle. It entails conducting exhaustive searches of all nodes by moving forward if
possible and backtracking, if necessary. To visit the next node, pop the top node from the
stack and push all of its nearby nodes into a stack. Topological sorting, scheduling problems,
graph cycle detection, and solving puzzles with just one solution, such as a maze or a sudoku
puzzle, all employ depth-first search algorithms. Other applications include network analysis,
such as determining if a graph is bipartite.

Algorithm:

1. Start at the source node.

2. Mark the source node as visited.

3. Visit the node and process it (e.g., print it).

4. Recursively visit all unvisited neighbors of the current node.

5. Repeat step 4 until no unvisited neighbors are left.

6. Backtrack to the previous node and continue the process for other unvisited branches.

Advantages of DFS :

1 The memory requirement is linear with respect to nodes.

2 Less time and space complexity compared to Breadth First Search (BFS).

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
7
CS3EA10/CB3CO14: Artificial Intelligence Experiment no-2

Experiment Title : Implement Depth First Search Page 2 of 5


Algorithm.

3 The solution can be found out without much more search.

4 DFS assures that the solution will be found if it exists.

5. DFS has huge applications in graph theory.

Disadvantages of DFS:

1 The run time may exceed when the goal node is unknown.

2 The algorithm may be reiterating itself without further appreciative progress.

3 There is a fear of an infinite loop in DFS, similar to BFS.

4 DFS is not guaranteed to find the solution.

5 There is no guarantee to find a minimal solution if more than one solution exists.

Time Complexity of DFS: The time complexity of DFS is O(V + E), where V is the number
of vertices, and E is the number of edges in the graph.

Space Complexity of DFS: The space complexity of DFS is O(V), where V is the number of
vertices.

Code:

#include <iostream>

#include <list>

#include <unordered_map>

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
8
CS3EA10: Artificial Intelligence Experiment no-2

Experiment Title : Implement Depth First Search Page 3 of 5


Algorithm.

class Graph {

std::unordered_map<int, std::list<int>> adjList;

public:

void addEdge(int v, int w) {

adjList[v].push_back(w);

void dfs(int vertex, std::unordered_map<int, bool>& visited) { visited[vertex] =

true;

std::cout << vertex << " ";

for (int neighbor : adjList[vertex]) {

if (!visited[neighbor]) {

dfs(neighbor, visited);

void depthFirstSearch(int start) {

std::unordered_map<int, bool> visited;

for (const auto& pair : adjList) {

visited[pair.first] = false;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
9
CS3EA10: Artificial Intelligence Experiment no-2

Experiment Title : Implement Depth First Search Page 4 of 5


Algorithm.

std::cout << "DFS starting from vertex " << start << ":" << std::endl;

dfs(start, visited);

};

int main() {

Graph g;

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.depthFirstSearch(2);

return 0;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
10
CS3EA10: Artificial Intelligence Experiment no-2

Experiment Title : Implement Depth First Search Page 5 of 5


Algorithm.

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
11
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 1 of 9


Tic Tac Toe

Objective : Write a program to implement Tic Tac Toe

Defination : Tic-Tac-Toe, also known as Noughts and Crosses, is a classic two-player game
where the objective is to be the first to form a straight line of your symbol (either "X" or "O")
on a 3x3 grid. Players take turns placing their symbols on the grid, and the game ends when
one player wins, or the grid is completely filled, resulting in a draw.

Tic-Tac-Toe Algorithm:

1. Initialize an empty 3x3 grid.

2. Alternate between the two players, taking turns to place their symbol (X or O) on an
empty cell of the grid.

3. After each move, check if the current player has won by forming a horizontal,
vertical, or diagonal line of their symbols.

4. If a player wins or the grid is completely filled, the game ends.

5. Display the result, whether one player wins, it's a draw, or the game continues.

Advantages of Tic-Tac-Toe:

1. Simplicity: Tic-Tac-Toe is easy to understand and play, making it suitable for all
ages.

2. Quick Gameplay: The game typically doesn't take a long time to finish.

3. Strategic Thinking: It involves basic strategic thinking and planning.

Disadvantages of Tic-Tac-Toe:

1. Limited Complexity: Tic-Tac-Toe can become repetitive and predictable, especially


among experienced players.

2. Tendency for Draws: With optimal play, Tic-Tac-Toe often ends in a draw.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
12
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 2 of 9


Tic Tac Toe

Complexity of Tic-Tac-Toe: Tic-Tac-Toe is a solved game, meaning that with perfect play
by both players, the outcome is either a draw or a win for the player going first (X).

Code:

#include <bits/stdc++.h>

using namespace std; #define COMPUTER 1


#define HUMAN 2

#define SIDE 3

#define COMPUTERMOVE 'O'

#define HUMANMOVE 'X'

void showBoard(char board[][SIDE])

printf("\n\n");

printf("\t\t\t %c | %c | %c \n", board[0][0],


board[0][1], board[0][2]);
printf("\t\t\t--------------\n");

printf("\t\t\t %c | %c | %c \n", board[1][0],

board[1][1], board[1][2]);

printf("\t\t\t--------------\n");

printf("\t\t\t %c | %c | %c \n\n", board[2][0],

board[2][1], board[2][2]);

return;

}
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
13
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 3 of 9


Tic Tac Toe

void showInstructions()

printf("\t\t\t Tic-Tac-Toe\n\n");

printf("Choose a cell numbered from 1 to 9 as below"

" and play\n\n");

printf("\t\t\t 1 | 2 | 3 \n");

printf("\t\t\t--------------\n");

printf("\t\t\t 4 | 5 | 6 \n");

printf("\t\t\t--------------\n");

printf("\t\t\t 7 | 8 | 9 \n\n");

printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");

return;

void initialise(char board[][SIDE], int moves[])

{ srand(time(NULL));

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

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

board[i][j] = ' ';

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
14
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 4 of 9


Tic Tac Toe

for (int i = 0; i < SIDE * SIDE; i++)


moves[i] = i;
random_shuffle(moves, moves + SIDE * SIDE);
return;
}

void declareWinner(int whoseTurn)

if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n"); return;
}

bool rowCrossed(char board[][SIDE])

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

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

board[i][1] == board[i][2] &&

board[i][0] != ' ')


return (true);
}

return (false);

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
15
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 5 of 9


Tic Tac Toe

bool columnCrossed(char board[][SIDE])

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

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

board[1][i] == board[2][i] &&

board[0][i] != ' ')

return (true);

return (false);

bool diagonalCrossed(char board[][SIDE])

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

board[1][1] == board[2][2] &&

board[0][0] != ' ')

return (true);

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

board[1][1] == board[2][0] &&

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
16
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 6 of 9


Tic Tac Toe

board[0][2] != ' ')

return (true);

return (false);

bool gameOver(char board[][SIDE])

return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board));

void playTicTacToe(int whoseTurn)

char board[SIDE][SIDE];

int moves[SIDE * SIDE];

initialise(board, moves);

showInstructions();

int moveIndex = 0, x, y;

while (gameOver(board) == false &&

moveIndex != SIDE * SIDE)

{ if (whoseTurn == COMPUTER)

{
x = moves[moveIndex] / SIDE;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
17
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 7 of 9


Tic Tac Toe

y = moves[moveIndex] % SIDE;

board[x][y] = COMPUTERMOVE;

printf("COMPUTER has put a %c in cell %d\n",

COMPUTERMOVE, moves[moveIndex] + 1);

showBoard(board);

moveIndex++;

whoseTurn = HUMAN;

else if (whoseTurn == HUMAN)

x = moves[moveIndex] / SIDE;

y = moves[moveIndex] % SIDE;

board[x][y] = HUMANMOVE;

printf("HUMAN has put a %c in cell %d\n",

HUMANMOVE, moves[moveIndex] + 1);

showBoard(board);

moveIndex++;

whoseTurn = COMPUTER;

} }

if (gameOver(board) == false &&


Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
18
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 7 of 9


Tic Tac Toe

moveIndex == SIDE * SIDE)

printf("It's a draw\n");

else

{
if (whoseTurn == COMPUTER)

whoseTurn = HUMAN;

else if (whoseTurn == HUMAN)

whoseTurn = COMPUTER;

declareWinner(whoseTurn);

return;

int main()

playTicTacToe(COMPUTER);

return (0);

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
19
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 8 of 9


Tic Tac Toe

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
20
CS3EA10: Artificial Intelligence Experiment no-3

Experiment Title : Write a program to implement Page 9 of 9


Tic Tac Toe

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
21
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 1 of 6


8 puzzle problem

Objective: Write a program to implement 8 puzzle problem

Definition: The 8-puzzle problem is a classic puzzle and an example of an unsolvable puzzle in its
general form. It is played on a 3x3 grid with 8 numbered tiles and one empty space. The objective is to
rearrange the tiles from an arbitrary initial configuration to a goal configuration, typically arranged in
ascending order. You can only slide a tile into the empty space, and the goal is to achieve the desired
configuration in as few moves as possible.

Algorithm:

1. Start with an initial configuration of the puzzle and a goal configuration.

2. Create a search tree where each node represents a state of the puzzle.

3. Use a search algorithm (e.g., A* search, Breadth-First Search) to traverse the search
tree, expanding nodes and generating successor states.

4. Maintain a priority queue or open list to explore the most promising nodes.

5. Continue the search until a goal state is reached or all possible states are explored.

Advantages:

1. It serves as a classic problem in artificial intelligence and search algorithms.

2. Provides a benchmark for testing heuristic search algorithms.

3. Offers a practical application for pathfinding in games and robotics.

Disadvantages :

1. The general form of the 8-puzzle problem is unsolvable, meaning not all initial
configurations can be solved.

2. Solving it optimally can be computationally expensive for larger puzzles.

3. Depending on the initial configuration, finding a solution may require a large number
of moves.
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
22
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 2 of 6


8 puzzle problem

Complexity of 8-Puzzle Problem: The time and space complexity of solving the 8-puzzle
problem depends on the search algorithm used. In the worst case, the number of possible
states to explore can be vast, especially for larger puzzles. Heuristic search algorithms, like
A*, can significantly reduce the search space.

Code:

#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;
const int N = 3;
struct State {
vector<vector<int>> board;
int moves;
int heuristic;

bool operator>(const State& other) const {

return moves + heuristic > other.moves + other.heuristic;

}};

const int dx[] = {-1, 1, 0, 0};

const int dy[] = {0, 0, -1, 1};

bool isValid(int x, int y) {

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

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
23
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 3 of 6


8 puzzle problem

int calculateHeuristic(const vector<vector<int>>& board) {


int h = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int value = board[i][j];
if (value != 0) {

int targetX = (value - 1) / N;


int targetY = (value - 1) % N;
h += abs(targetX - i) + abs(targetY - j);

} } }

return h;

int solvePuzzle(vector<vector<int>> initial) {

priority_queue<State, vector<State>, greater<State>> pq;

map<vector<vector<int>>, int> distance;

vector<vector<int>> goal(N, vector<int>(N, 0));

int value = 1;

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

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

goal[i][j] = value;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
24
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 4 of 6


8 puzzle problem

value++;
} }

goal[N - 1][N - 1] = 0;

State start;

start.board = initial;
start.moves = 0;
start.heuristic = calculateHeuristic(initial);
pq.push(start);
distance[initial] = 0;
while (!pq.empty()) {
State current = pq.top();

pq.pop();

if (current.board == goal) {
return current.moves;
}
int x, y;

for (x = 0; x < N; x++) {


for (y = 0; y < N; y++) {
if (current.board[x][y] == 0) {
break;
} }

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
25
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 5 of 6


8 puzzle problem

if (y < N && x < N) {


break;
} }

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


int newX = x + dx[i];
int newY = y + dy[i];

if (isValid(newX, newY)) {
State next = current;
swap(next.board[x][y], next.board[newX][newY]);

if (!distance.count(next.board) || current.moves + 1 < distance[next.board]) {


next.moves = current.moves + 1;
next.heuristic = calculateHeuristic(next.board);
pq.push(next);
distance[next.board] = next.moves;

} } } }

return -1;

int main() {

vector<vector<int>> initial = {{1, 2, 3}, {4, 5, 6}, {0, 7, 8}};


int moves = solvePuzzle(initial);
if (moves != -1) {
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
26
CS3EA10: Artificial Intelligence Experiment no-4

Experiment Title : Write a program to implement Page 6 of 6


8 puzzle problem

cout << "Minimum number of moves to solve the puzzle: " << moves << endl;

} else {

cout << "The puzzle is unsolvable." << endl;

return 0;

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
27
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 1 of 6


Water jug problem

Objective: Write a program to implement Water jug problem

Definition: The Water Jug Problem is a classic mathematical puzzle that involves two jugs of different
capacities, usually referred to as "Jug X" and "Jug Y." The goal is to measure a specific amount of water
(referred to as "Z" liters) using these two jugs. The problem requires finding a sequence of actions, such
as filling, emptying, or pouring water between the jugs, to obtain the desired amount of water.

Example:

Suppose you have two jugs:

Jug X with a capacity of 4 liters

Jug Y with a capacity of 3 liters

Your goal is to measure 2 liters of water using these jugs. The Water Jug Problem is to find a
series of actions to achieve this target.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
28
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 2 of 6


Water jug problem

Algorithm:

To solve the Water Jug Problem, you can use the Breadth-First Search (BFS) algorithm.
Here's a high-level overview of the algorithm:

1. Create a queue to store states of the jugs and an empty set to store visited states.
2. Start with an initial state (0, 0), where both jugs are empty.
3. Add this state to the queue.
4. While the queue is not empty:

a. Pop a state from the queue.

b. Generate all possible next states by applying the following operations:

 Fill Jug X.
 Fill Jug Y.
 Empty Jug X.
 Empty Jug Y.
 Pour water from Jug X to Jug Y until Jug X is empty or Jug Y is full.
 Pour water from Jug Y to Jug X until Jug Y is empty or Jug X is full.

c. Check each generated state:

 If it's the target state (with Z liters in one of the jugs), return the sequence of
operations.
 If it's not visited, add it to the queue and mark it as visited.

Advantages:

 BFS guarantees that the solution found will be the shortest in terms of the number of
steps required to reach the target state.
 It is a simple and straightforward way to solve this problem.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
29
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 3 of 6


Water jug problem

Disadvantages:

 The algorithm can be inefficient for large values of jug capacities and target volumes,
as it explores many states.
 It may not be the most efficient algorithm for finding solutions to this problem in real-
world scenarios.

Complexity:

The time complexity of the BFS algorithm is O(X * Y), where X and Y are the capacities of
the two jugs. The space complexity can be up to O(X * Y) as well.

Code:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void printSolution(vector<pair<int, int>> steps) {

for (const auto& step : steps) {

cout << "Step " << step.first << ": ";

if (step.second == 1) {

cout << "Pour water from jug X to jug Y." << endl;

} else if (step.second == 2) {

cout << "Pour water from jug Y to jug X." << endl;
} else if (step.second == 3) {

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
30
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 4 of 6


Water jug problem

cout << "Fill jug X." << endl;

} else {

cout << "Fill jug Y." << endl;

} } }

vector<pair<int, int>> solveWaterJugProblem(int jugX, int jugY, int target) {

vector<pair<int, int>> steps; // To store the solution steps

int x = 0, y = 0; // Initial water levels in both jugs

int step = 1; // Step counter

while (x != target && y != target) {

if (x == 0) {

x = jugX;

steps.push_back(make_pair(step++, 3));

} else if (y == jugY) {

y = 0;

steps.push_back(make_pair(step++, 2));

} else {

int pourAmount = min(x, jugY - y);

x -= pourAmount;

y += pourAmount;

steps.push_back(make_pair(step++, 1));
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
31
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 5 of 6


Water jug problem

} }

return steps;

int main() {

int jugX, jugY, target;

cout << "Enter the capacity of jug X: ";

cin >> jugX;

cout << "Enter the capacity of jug Y: ";

cin >> jugY;

cout << "Enter the target amount of water: ";

cin >> target;

vector<pair<int, int>> solution = solveWaterJugProblem(jugX, jugY, target);

if (solution.empty()) {

cout << "No solution exists." << endl;

} else {

cout << "Solution steps:" << endl;

printSolution(solution);

return 0;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
32
CS3EA10: Artificial Intelligence Experiment no-5

Experiment Title : Write a program to implement Page 6 of 6


Water jug problem

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
33
CS3EA10: Artificial Intelligence Experiment no-6

Experiment Title: Write a Program to Implement Page 1 of 4


Traveling Salesman Problem.

Objective: Write a Program to Implement Traveling Salesman Problem.

Defination: Given a set of cities and the distance between every pair of cities, the problem
is to find the shortest possible route that visits every city exactly once and returns to the
starting point. Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian
cycle problem is to find if there exists a tour that visits every city exactly once. Here we
know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such
tours exist, the problem is to find a minimum weight Hamiltonian Cycle.

For example, consider the graph shown in the figure on the right side. A TSP tour in the
graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. The problem is a
famous NP-hard problem.

Examples:
Output of Given Graph:
minimum weight Hamiltonian Cycle :
10 + 25 + 30 + 15 := 80
Algorithm:

1. Consider city 1 as the starting and ending point. Since the route is cyclic, we can
consider any point as a starting point.
2. Generate all (n-1)! permutations of cities.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
34
3. Calculate the cost of every permutation and keep track of the minimum cost
permutation.

CS3EA10: Artificial Intelligence Experiment no-6

Experiment Title: Write a Program to Implement Page 2 of 4


Traveling Salesman Problem.

4. Return the permutation with minimum cost.

Advantages:

 Guaranteed to find the optimal solution.


 Real-world applicability for route planning and logistics.
 Suitable for small to medium-sized instances of TSP.

Disadvantages:

 Exponential time complexity, making it inefficient for large problem sizes.


 High time and space complexity; impractical for a large number of cities
 Solution quality depends on input data and choice of heuristic.
 Heuristic algorithms do not guarantee optimality.

Time complexity: O(n!) where n is the number of vertices in the graph. This is because the
algorithm uses the next_permutation function which generates all the possible permutations
of the vertex set.
Auxiliary Space: O(n) as we are using a vector to store all the vertices.

Code:

#include <bits/stdc++.h>

using namespace std;

#define V 4

int travllingSalesmanProblem(int graph[][V], int s)

vector<int> vertex;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
35
CS3EA10: Artificial Intelligence Experiment no-6

Experiment Title: Write a Program to Implement Page 3 of 4


Traveling Salesman Problem.

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

if (i != s)

vertex.push_back(i);

int min_path =

INT_MAX; do {

int current_pathweight = 0;

int k = s;

for (int i = 0; i < vertex.size(); i++) {

current_pathweight += graph[k][vertex[i]]

k = vertex[i];

current_pathweight += graph[k][s];

min_path = min(min_path, current_pathweight);

} while (

next_permutation(vertex.begin(), vertex.end()));

return min_path;

int main()

int graph[][V] = { { 0, 10, 15, 20 },

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
36
CS3EA10: Artificial Intelligence Experiment no-6

Experiment Title: Write a Program to Implement Page 4 of 4


Traveling Salesman Problem.

{ 10, 0, 35, 25 },

{ 15, 35, 0, 30 },

{ 20, 25, 30, 0 } };

int s = 0;

cout << travllingSalesmanProblem(graph, s) << endl;

return 0;

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
37
CS3EA10: Artificial Intelligence Experiment no-7

Experiment Title: Write a program to implement Page 1 of 5


Tower Of Hanoi.

Objective: Write a program to implement Tower of Hanoi

Definition: Tower of Hanoi is a mathematical puzzle where we have three rods (A, B,
and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e.,
the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is
to move the entire stack to another rod (here considered C), obeying the following simple
rules:

 Only one disk can be moved at a time.


 Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
 No disk may be placed on top of a smaller disk.

Examples:
Input: 2
Output: Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Input: 3
Output: Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
38
CS3EA10: Artificial Intelligence Experiment no-7

Experiment Title: Write a program to implement Page 2 of 5


Tower Of Hanoi.

Image illustration for 3 disks

Follow the steps below to solve the problem:


 Create a function towerOfHanoi where pass the N (current number of
disk), from_rod, to_rod, aux_rod.
 Make a function call for N – 1 th disk.
 Then print the current the disk along with from_rod and to_rod
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
39
CS3EA10: Artificial Intelligence Experiment no-7

Experiment Title: Write a program to implement Page 3 of 5


Tower Of Hanoi.

 Again make a function call for N – 1 th disk.

Algorithm:
 Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
 Shift last disk from ‘A’ to ‘C’.
 Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.

Advantages:

 Simplicity: The problem is simple to understand and explain.

 Recursive Nature: The algorithm for solving the Tower of Hanoi problem is
naturally recursive, making it a good example of recursion in computer science
and mathematics.

Disadvantages:

 Inefficiency: The Tower of Hanoi algorithm is not efficient for large numbers of
disks. It has exponential time complexity, O(2^n), which makes it impractical for a
large number of disks.
 Limited Practical Use: The Tower of Hanoi problem has limited direct practical
applications, and its primary value is in teaching recursive thinking.

Time complexity: O(2N), There are two possibilities for every disk. Therefore, 2 * 2 * 2 * .
. . * 2(N times) is 2N

Auxiliary Space: O(N), Function call stack space

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
40
CS3EA10: Artificial Intelligence Experiment no-7

Experiment Title: Write a program to implement Page 4 of 5


Tower Of Hanoi.

Code:

#include <bits/stdc++.h>

using namespace std;

void towerOfHanoi(int n, char from_rod, char to_rod,

char aux_rod)

{ if (n == 0) {

return;

towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

cout << "Move disk " << n << " from rod " << from_rod

<< " to rod " << to_rod << endl;

towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

int main()

int N = 3;

towerOfHanoi(N, 'A', 'C', 'B');

return 0;

}
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
41
CS3EA10: Artificial Intelligence Experiment no-7

Experiment Title: Write a program to implement Page 5 of 5


Tower Of Hanoi.

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
42
CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 1 of 6


Monkey Banana Problem.

Objective: Write a Program to Implement Monkey Banana Problem.

Definition: The Monkey and Banana problem is a classic AI problem where a monkey is
placed in a room with a banana hanging from the ceiling. The monkey's goal is to reach the
banana. To do so, the monkey can perform various actions, such as moving around the room,
grabbing the banana, climbing a box, and pushing the box.

Example:

Consider a 4x4 grid room with coordinates (1,1) in the top left corner and (4,4) in the bottom
right corner. The initial positions are as follows:

 Monkey's initial position: (1, 1)


 Banana's position: (3, 3)
 Box's position: (2, 2)

Here's a representation of the room:

In this example:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
43
CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 2 of 6


Monkey Banana Problem.

 "M" represents the monkey.

"B" represents both the box (on the floor) and the banana (hanging from the ceiling).
Algorithm:

The Monkey and Banana problem can be solved using a simple goal-based search algorithm,
such as depth-first search or breadth-first search. The algorithm involves the following steps:

1. Initialize the monkey's position and state (without the box).

2. While the monkey has not reached the banana:

a. Choose an action (move, grab, climb, or push).

b. Perform the chosen action.

c. Check if the monkey has reached the banana.

d. If not, repeat the process.

Advantages:

 A simple problem that can be used to teach search algorithms and AI concepts.
 Provides a foundation for understanding goal-based planning and reasoning.
Disadvantages:

 The problem assumes perfect knowledge of the environment.


 Doesn't consider uncertainty or partial observability, which are common in real-world
scenarios.

Complexity:

The problem's complexity depends on the initial positions of the monkey, banana, and box. In
the worst case, the monkey might need to explore the entire room to reach the banana,
resulting in a time complexity that can be exponential in the worst case.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
44
CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 3 of 6


Monkey Banana Problem.

Code:

#include <iostream>

using namespace std;

const int roomWidth = 4;

const int roomHeight = 4;

class MonkeyBananaProblem {

public:

MonkeyBananaProblem() {

monkeyX = 1;

monkeyY = 1;

bananaX = 3;

bananaY = 3;

void moveMonkey(int dx, int dy) {

int newX = monkeyX + dx;

int newY = monkeyY + dy;

if (isValidPosition(newX, newY)) {

monkeyX = newX;

monkeyY = newY;

} }

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
45
bool isGoalState() {

CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 4 of 6


Monkey Banana Problem.

return (monkeyX == bananaX) && (monkeyY == bananaY);

int getMonkeyX() const {

return monkeyX;

int getMonkeyY() const {

return monkeyY;

int getBananaX() const {

return bananaX;}

int getBananaY() const {

return bananaY;

private:

int monkeyX, monkeyY;

int bananaX, bananaY;

bool isValidPosition(int x, int y) {

return (x >= 1 && x <= roomWidth && y >= 1 && y <= roomHeight);

} };

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
46
int main() {

MonkeyBananaProblem problem;

CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 5 of 6


Monkey Banana Problem.

cout << "Initial State:" << endl;

cout << "Monkey: (" << problem.getMonkeyX() << ", " << problem.getMonkeyY() << ")"
<< endl;

cout << "Banana: (" << problem.getBananaX() << ", " << problem.getBananaY() << ")"
<< endl;

cout << "Solving..." << endl;

while (!problem.isGoalState()) {

if (problem.getMonkeyX() < problem.getBananaX())

problem.moveMonkey(1, 0);

else if (problem.getMonkeyX() > problem.getBananaX())

problem.moveMonkey(-1, 0);

else if (problem.getMonkeyY() < problem.getBananaY())

problem.moveMonkey(0, 1);else if (problem.getMonkeyY() >

problem.getBananaY()) problem.moveMonkey(0, -1);

cout << "Final State:" << endl;

cout << "Monkey: (" << problem.getMonkeyX() << ", " << problem.getMonkeyY() << ")"
<< endl;

cout << "Banana: (" << problem.getBananaX() << ", " << problem.getBananaY() << ")"
<< endl;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
47
CS3EA10: Artificial Intelligence Experiment no-8

Experiment Title: Write a Program to Implement Page 6 of 6


Monkey Banana Problem.

cout << "Monkey reached the banana!" << endl;

return 0;

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
48
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 1 of 6


N-Queens Problem

Objective: Write a Program to Implement N-Queens Problem.

Defination: The N-Queens problem is a classic combinatorial puzzle that involves placing N
queens on an NxN chessboard in such a way that no two queens threaten each other. In other
words, no two queens can be in the same row, column, or diagonal.

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no
two queens attack each other.
For example, the following is a solution for the 4 Queen problem.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
49
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 2 of 6


N-Queens Problem

The expected output is in the form of a matrix that has ‘Q‘s for the blocks where queens are
placed and the empty spaces are represented by ‘.’ . For example, the following is the
output matrix for the above 4-Queen solution.

N Queen Problem using Backtracking:


The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this
row and column as part of the solution. If we do not find such a row due to clashes, then we
backtrack and return false.

Below is the recursive tree of the above approach:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
50
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 3 of 6


N-Queens Problem

Algorithm:
1. Start in the leftmost column.
2. If all queens are placed, return true (base case).
3. Try all rows in the current column. For each row:
a. If the queen can be safely placed in this row and column, mark this cell as part of
the solution.
b. Recur to place queens in the next column.
c. If placing queens in the next column leads to a solution, return true.
d. If placing queens in the next column does not lead to a solution, unmark this cell
(backtrack) and return false.

4. If all rows have been tried and none worked, return false to trigger backtracking.

Advantages:
 The N-Queens problem is a well-known problem used for teaching and learning
backtracking algorithms.
 It has real-world applications in areas like scheduling, job assignment, and resource
allocation.

Disadvantages:

 The N-Queens problem can be computationally expensive for larger N values.


 The number of solutions grows rapidly with N, making it impractical to solve for
very large boards.

Complexity:

 The time complexity of solving the N-Queens problem is O(N!).


 The space complexity is O(N).

Code:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
51
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 4 of 6


N-Queens Problem

#include <bits/stdc++.h>
#define N 4
using namespace std;
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
if(board[i][j])

cout << "Q ";


else cout<<". ";
printf("\n");
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return false;

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)

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
52
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 5 of 6


N-Queens Problem

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;
}
}
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },

{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false)
{
cout << "Solution does not exist";
return false;
}
printSolution(board);
return true;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
53
CS3EA10: Artificial Intelligence Experiment no-9

Experiment Title: Write a Program to Implement Page 6 of 6


N-Queens Problem

int main()

{
solveNQ();
return 0;
}

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
54
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 1 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

Objective: Write a Program to Implement Mini-max and Alpha beta pruning algorithm.

Definition: Mini-max problem:

Mini-max is a kind of backtracking algorithm that is used in decision making and game
theory to find the optimal move for a player, assuming that your opponent also plays
optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe,
Backgammon, Mancala, Chess, etc.
In Minimax the two players are called maximizer and minimizer. The maximizer tries to get
the highest score possible while the minimizer tries to do the opposite and get the lowest
score possible.
Every board state has a value associated with it. In a given state if the maximizer has upper
hand then, the score of the board will tend to be some positive value. If the minimizer has
the upper hand in that board state then it will tend to be some negative value. The values of
the board are calculated by some heuristics which are unique for every type of game.

Example:
Consider a game which has 4 final states and paths to reach final state are from root to 4
leaves of a perfect binary tree as shown below. Assume you are the maximizing player and
you get the first chance to move, i.e., you are at the root and your opponent at next
level. Which move you would make as a maximizing player considering that your opponent
also plays optimally?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
55
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 2 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and
makes a decision.
 Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice
between 3 and 5. Being the minimizer it will definitely choose the least among both,
that is 3
 Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice
between 2 and 9. He will choose 2 as it is the least among the two values.

Being the maximizer you would choose the larger value that is 3. Hence the optimal move
for the maximizer is to go LEFT and the optimal value is 3.
Now the game tree looks like below :

The above tree shows two possible scores when maximizer makes left and right moves.

Algorithm:

1. If the game has reached a terminal state (win, lose, or draw), return the utility value.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
56
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 3 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

2. If it's the player's turn, maximize the utility value by choosing the move with the highest
value.

3. If it's the opponent's turn, minimize the utility value by choosing the move with the lowest
value.

4. Recursively apply the algorithm until a terminal state is reached.

Advantages:

 Guarantees optimal play for both players in perfect information games.


 Suitable for deterministic, discrete, and sequential games.

Disadvantages:

 Computationally expensive for complex games due to the exponential growth of


possibilities.
 Not suitable for games with incomplete or uncertain information.

Time complexity : O(b^d) b is the branching factor and d is count of depth or ply of graph
or tree.

Space Complexity : O(bd) where b is branching factor into d is maximum depth of tree
similar to DFS.
Code:

#include<bits/stdc++.h>

using namespace std;

int minimax(int depth, int nodeIndex, bool isMax,

int scores[], int h)


Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
57
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 4 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

if (depth == h)

return scores[nodeIndex];
if (isMax)
return max(minimax(depth+1, nodeIndex*2, false, scores, h),
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
else

return min(minimax(depth+1, nodeIndex*2, true, scores, h),


minimax(depth+1, nodeIndex*2 + 1, true, scores, h)); }

int log2(int n)

return (n==1)? 0 : 1 + log2(n/2);

int main() {

int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};

int n = sizeof(scores)/sizeof(scores[0]);

int h = log2(n);

int res = minimax(0, 0, true, scores, h);

cout << "The optimal value is : " << res << endl;

return 0;

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
58
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 5 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

Output:

(B) Definitions: Alpha beta pruning:

Alpha-beta pruning is a modified version of the minimax algorithm. It is an optimization


technique for the minimax algorithm.As we have seen in the minimax search algorithm that
the number of game states it has to examine are exponential in depth of the tree. Since we
cannot eliminate the exponent, but we can cut it to half. Hence there is a technique by which
without checking each node of the game tree we can compute the correct minimax decision,
and this technique is called pruning. This involves two threshold parameter Alpha and beta
for future expansion, so it is called alpha-beta pruning. It is also called as Alpha-Beta
Algorithm.

Alpha-beta pruning can be applied at any depth of a tree, and sometimes it not only prune the
tree leaves but also entire sub-tree.

The two-parameter can be defined as:

a. Alpha: The best (highest-value) choice we have found so far at any point
along the path of Maximizer. The initial value of alpha is -∞.
b. Beta: The best (lowest-value) choice we have found so far at any point along
c.
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
59
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 6 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

the path of Minimizer. The initial value of beta is +∞.

The Alpha-beta pruning to a standard minimax algorithm returns the same move as the
standard algorithm does, but it removes all the nodes which are not really affecting the final
decision but making algorithm slow. Hence by pruning these nodes, it makes the algorithm
fast.

The main condition which required for alpha-beta pruning is:

α>=β

Algorithm:

Here's a basic outline of the alpha-beta pruning algorithm:

1Initialize alpha to negative infinity and beta to positive infinity.

2. Perform a depth-first search of the game tree.

3. At each node, evaluate all legal moves.

4. Update alpha and beta values based on the player (maximizer or minimizer).

5. Prune branches that cannot affect the final decision (alpha-beta cutoff).

6. Continue until the entire tree is explored.

Advantages:

 Significantly reduces the number of nodes explored.


 Improves the efficiency of the minimax algorithm.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
60
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 7 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

Disadvantages:

 Assumes that the opponent plays optimally, so may not be as effective against
suboptimal opponents.
 Implementation can be complex.

Complexity:
The time complexity of the alpha-beta pruning algorithm is O(b^(d/2)), where b is the
branching factor and d is the depth of the tree.

Code:
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
const int MIN = -1000;

int minimax(int depth, int nodeIndex,


bool maximizingPlayer,
int values[], int alpha,
int beta)
{
if (depth == 3)
return values[nodeIndex];
if (maximizingPlayer)
{
int best = MIN;
for (int i = 0; i < 2; i++)
{
int val = minimax(depth + 1, nodeIndex * 2 + i,
false, values, alpha, beta);
best = max(best, val);
alpha = max(alpha, best);
if (beta <= alpha)
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
61
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 8 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

break;
}
return best;
}
else
{
int best = MAX;
for (int i = 0; i < 2; i++)
{
int val = minimax(depth + 1, nodeIndex * 2 + i,
true, values, alpha, beta);
best = min(best, val);
beta = min(beta, best);

if (beta <= alpha)


break;
}
return best;
}
}
int main()
{
int values[8] = { 3, 5, 6, 9, 1, 2, 0, -1 };
cout <<"The optimal value is : "<< minimax(0, 0, true, values, MIN, MAX);;
return 0;
}
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
62
CS3EA10: Artificial Intelligence Experiment no-10

Experiment Title: a Program to Implement Page 9 of 9


(A)Minimax and(B) Alpha beta pruning algorithm.

Output:

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University Ajeet Singh Rajput
63

You might also like