You are on page 1of 11

AIM: Write a program to perform Depth First Search (DFS).

ALGORITHM: Algorithm for DFS is as follows:


1. Start with the root node on the top of a stack.
2. Take the top item and add it to the visited list.
3. Create a list of that vertex’s adjacent nodes.
4. Add the ones which are not in visited list.
5. Keep repeating the previous 3-steps until the stack is empty.

CODE: The code for the DFS program is as follows:


#include <stdio.h>
#include <stdlib.h>

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int v);

struct Graph {
int numVertices;
int* visited;

struct node** adjLists;


};

// DFS algo
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while (temp != NULL) {


int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;

Page 1
}
}

struct node* createNode(int v) {


struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int vertices) {


struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {


struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

void printGraph(struct Graph* graph) {


int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

int main() {
Page 2
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);

printGraph(graph);

DFS(graph, 2);

return 0;
}

OUTPUT: The output for the DFS program is as follows:

Page 3
OBJECTIVE: Write a program to perform Breadth First Search (BFS).

AIM: To find the target node.

ALGORITHM: Algorithm for BFS is as follows:


1. Create a queue data structure to store nodes to be processed.
2. Create a set to keep track of visited nodes.
3. Enqueue the “start” node into the queue and mark it as visited in the set.
4. While the queue is not empty, repeat steps 5-7.
5. Dequeue a node from the front of the queue.
6. Process the node.
7. Enqueue all unvisited neighbours deque node in queue and mark as visited.
8. If there are no more nodes in the queue, the BFS is complete.

CODE: The code for the BFS program is as follows:


import collections
def bfs(graph, root):

visited, queue = set(), collections.deque([root])


visited.add(root)

while queue:

vertex = queue.popleft()
print(str(vertex) + " ", end="")

for neighbour in graph[vertex]:


if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)

if __name__ == '__main__':
graph = {'A' : ['B','C'], 'B' : ['D','E'], 'C' : ['F'], 'D' : [], 'E' : [], 'F' : []}
print("Breadth First Traversal: ")
bfs(graph, 'A')

Page 4
OUTPUT: The output for the BFS program is as follows:

Page 5
OBJECTIVE: Write a program for the Water Jug problem.

AIM: To use the jugs to measure out a specific amount of water by filling
and emptying the jugs in a particular order.

ALGORITHM: The algorithm for the water jug problem is as follows:


1. Define capacities: Jug A (capacity "A" litres), Jug B (capacity "B" litres).
2. Set target quantity: "C" litres.
3. Initialize current water levels: Jug A = 0, Jug B = 0.
4. Start with initial state: (0, 0).
5. While exploration queue is not empty:
* Dequeue state.
* If state matches target quantity "C", terminate successfully.
6. Generate valid next states: fill A, fill B, empty A, empty B, pour A to B, pour B to A.
* If state unexplored, enqueue.
* Mark state as explored.
7. If no solution found, terminate unsuccessfully.

CODE: The code for the Water Jug problem is as follows:


from collections import deque
def Solution(a, b, target):
m = {}
isSolvable = False
path = []

q = deque()
q.append((0, 0))

while (len(q) > 0):


u = q.popleft()
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
path.append([u[0], u[1]])

Page 6
m[(u[0], u[1])] = 1
if (u[0] == target or u[1] == target):
isSolvable = True

if (u[0] == target):
if (u[1] != 0):
path.append([u[0], 0])
else:
if (u[0] != 0):
path.append([0, u[1]])

sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break

q.append([u[0], b]) # Filling Jug2


q.append([a, u[1]]) # Filling Jug1

for ap in range(max(a, b) + 1):


c = u[0] + ap
d = u[1] - ap
if (c == a or (d == 0 and d >= 0)):
q.append([c, d])

c = u[0] - ap
d = u[1] + ap

if ((c == 0 and c >= 0) or d == b):


q.append([c, d])

q.append([a, 0])
q.append([0, b])

if (not isSolvable):
print("Solution not possible")

if __name__ == '__main__':

Jug1, Jug2, target = 4, 3, 2


print("Path from initial state "
"to solution state ::")

Solution(Jug1, Jug2, target)

Page 7
OUTPUT: The output for the Water Jug problem is as follows:

Page 8
OBJECTIVE: To implement Magic Square using any heuristic technique of
AI.

AIM: The sum of all rows, columns and diagonals of the Magic Square must
be 15 in a 3x3 matrix.

ALGORITHM: The Algorithm for the Magic square is as follows:


1. Initialize by filling all the squares with zeroes in a 3x3 matrix.
2. Start to place the number 1 in centre of the top row.
3. Start to move diagonally up to the right.
4. If:
* It goes out of bound then wrap to the opposite side.
* The cell is occupied then move down and not up.
5. Repeat steps 3 to 4 until all cells are filled up.
6. Ensure that sum of all rows, columns and diagonals must be 15 only.

CODE: The code for the Magic square implementation is as follows:


def generate_3x3_magic_square():
magic_square = [[0] * 3 for i in range(3)]
num = 1
row, col = 0, 1

while num <= 9:


magic_square[row][col] = num
num += 1

new_row = (row - 1) % 3
new_col = (col + 1) % 3

if magic_square[new_row][new_col] == 0:
row, col = new_row, new_col
else:
row = (row + 1) % 3

return magic_square

def print_magic_square(matrix):
for row in matrix:
print(row)
Page 9
# Print the 3x3 magic square
magic_square = generate_3x3_magic_square()
print_magic_square(magic_square)

OUTPUT: The output for the above code is as follows:

Page 10
INTRODUCTION TO MATLAB

Engineers and scientists worldwide rely on MATLAB for their analytical and design tasks, which play a
crucial role in advancing various industries. MATLAB's matrix-based language provides an intuitive way to
perform computational mathematics. It also offers built-in graphics that facilitate data visualization and
interpretation. The user-friendly desktop environment encourages experimentation and fosters discovery.

MATLAB offers a comprehensive suite of tools and features that have undergone rigorous testing and are
designed to seamlessly work together. Beyond basic analysis, MATLAB empowers you to handle larger
datasets and extend your work to clusters and cloud computing resources. Furthermore, you can integrate
MATLAB code with other programming languages, allowing you to deploy your algorithms and applications
across web, enterprise, and production systems.

While working in MATLAB, you issue commands that create variables and call functions. For an
introduction:
• ans – Most recent answer
• clc – Clear Command Window
• diary – Log Command Window text to file
• format – Set output display format
• home – Send cursor home
• iskeyword – Determine whether input is MATLAB keyboard
• more – Control paged output in Command Window
• commandwindow – Select the Command Window
• commandhistory – Open Command History window

Page 11

You might also like