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

DAA Lab(extras)

The document outlines the implementation of various algorithms including Hamiltonian problem, Bellman-Ford for shortest paths, Kruskal's algorithm for Minimum Spanning Tree, and a Traveling Salesman Problem (TSP) solution, all using the GCC compiler. Each section includes the algorithm, program code, results, and complexity analysis, with complexities ranging from O(n!) for the Hamiltonian problem to O(m*n!) for Kruskal's algorithm. The document serves as a comprehensive guide for implementing these algorithms in C.

Uploaded by

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

DAA Lab(extras)

The document outlines the implementation of various algorithms including Hamiltonian problem, Bellman-Ford for shortest paths, Kruskal's algorithm for Minimum Spanning Tree, and a Traveling Salesman Problem (TSP) solution, all using the GCC compiler. Each section includes the algorithm, program code, results, and complexity analysis, with complexities ranging from O(n!) for the Hamiltonian problem to O(m*n!) for Kruskal's algorithm. The document serves as a comprehensive guide for implementing these algorithms in C.

Uploaded by

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

ASSIGNMENT NO : 16

PROBLEM STATEMENT :
Implement Hamiltonian problem. Mention the compiler used in your program.
Analyze the complexity value of your algorithm.

The compiler used here is GCC.

ALGORITHM :
Algorithm Hamiltonian(k)

// This algorithm uses the recursive formulation of

// backtracking to find all the Hamiltonian cycles

// of a graph. The graph is stored as an adjacency

// matrix G[1:n, 1:n].All cycles begin at node1.

repeat

{ // Generate values for x[k].

NextValue(k); // Assign a legal next value to x[k].

if (x[k] = 0) then return;

if (k = n) then write (x[1:n]);

else Hamiltonian(k+1);

} until (false);

AlgorithmNextValue(k)

// x[1:k-1] is a path of k-1 distinct vertices. If x[k]= 0, then


// no vertex has as yet been assigned to x[k]. After execution,

// x[k]is assigned to the next highest numbered vertex which

// does not already appear in x[1:k-1] and is connectedby

// an edge to x[k-1]. Otherwise x[k]=0.If k = n, then

// in addition x[k] is connected to x[1].

repeat

x[k]:=(x[k+ 1)mod(n + 1);// Next vertex.

if (x[k]= 0) then return;

if (G[x[k-1],x[k]] !=0)then

{ // Is there an edge?

for j :=1to k-1 do if (x[j]= x[k]) then break;

// Check for distinctness.

if (j = k) then // If true, then the vertex is distinct.

if ((k<n) or ((k= n) and G[x[n],x[1]]!= 0))

then return;

} until(false);

PROGRAM CODE :
#include<stdio.h>

#define SIZE 10
int n, g[SIZE][SIZE],x[SIZE],i,j;

int hamiltonian(int);

int nextval(int);

int main()

int s;

printf("Enter the no of vertices: ");

scanf("%d",&n);

printf("\nThe adjacency matrix is: ");

for(i=1;i<=n;i++)

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

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

printf("\nEnter the source vertex: ");

scanf("%d",&s);

x[1]=s;

for(i=2;i<=n;i++)

x[i]=0;

hamiltonian(2);

printf("%d",s);
}

int hamiltonian(int k)

while(1)

nextval(k);

if(x[k]==0)

return;

if(k==n)

printf("\nThe hamiltonian cycle is: ");

for(i=1;i<=n;i++)

printf("%d->",x[i]);

else

hamiltonian(k+1);

int nextval(int k)

while(1)

x[k]=(x[k]+1)%(n+1);
if(x[k]==0)

return;

if(g[x[k-1]][x[k]]!=0)

for(j=1;j<k;j++)

if(x[j]==x[k])

break;

if(j==k)

if((k<n)|| ((k==n) && (g[x[n]][x[1]]!=0)))

return;

RESULTS AND DISCUSSIONS :


Enter the no. of vertices in the graph: 5

Enter the adjacency matrix:

01001

10111

01010
01101

11000

Enter the starting vertex: 3

Hamiltonian cycle is: 3->4->5->1->2->3

--------------------------------

COMPLEXITY ANALYSIS :
1. In this algorithm the function Hamiltonian() will be called for n times.
2. Now the function NextValue() checks for every vertex(except itself and
the vertex already traversed)
3. So, each next vertex has (n-1) choices
4. Thus the loop or the cycle goes on like, n(n-1)(n-2)(n-3)……….. = n!

So, the final time complexity of the algorithm is O(n!).


ASSIGNMENT NO 11 :
PROBLEM STATEMENT :
Implement single source shortest path problem, allowing negative edge
weights, using proper algorithm design technique. Mention the compiler used
in your program. Analyze the complexity value of your algorithm.

The compiler used here is GCC.

ALGORITHM :
Algorithm bellman_ford(s)

//Here g[1:n][1:n] is an adjacency matrix, where n is no of vertices, dis[1:n] is


the distance array and s is the source vertex declared globally.

for i=1 upto n do

dis[i]=INF

dis[s]=0

for k=1 upto n-1 do

for i=1 upto n do

for j=1 upto n do

if(g[i ][j] !=INF and dis[i]!=INF and dis[i]+g[i][j]<dis[j])


then

dis[j]=dis[i]+g[i][j]
for i=1 upto n do

If(dis[i]!=INF) then

print: s->i=dis[i]

Else

print: s->i=INF

PROGRAM CODE :
#include<stdio.h>

#define SIZE 10

#define INF 9999

int g[SIZE][SIZE],dis[SIZE],n,s;

void bellman_ford(int);

void main()

int i,j;

printf("Enter the no of vertices: ");

scanf("%d",&n);

printf("\nEnter the source vertex: ");

scanf("%d",&s);

printf("\nEnter the adjacency matrix: ");

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

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

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

if(g[i][j]==0)

g[i][j]=INF;

bellman_ford(s);

void bellman_ford(int s)

int i,j,k;

for(i=1;i<=n;i++)

dis[i]=INF;

dis[s]=0;

for(k=1;k<=n-1;k++)

for(i=1;i<=n;i++)

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

if(g[i][j]!=INF && dis[i]!=INF && dis[i]+g[i][j]<dis[j])


dis[j]=dis[i]+g[i][j];

for(i=1;i<=n;i++)

if(dis[i]!=INF)

printf("\nThe path is: %d->%d = %d",s,i,dis[i]);

else

printf("\nThe path is: %d->%d = INF",s,i);

RESULTS AND DISCUSSION :


Enter the no of vertices: 5

Enter the source vertex: 1

Enter the adjacency matrix: 0 4 2 0 0

00323

01045

00000

0 0 0 -5 0
The path is: 1->1 = 0

The path is: 1->2 = 3

The path is: 1->3 = 2

The path is: 1->4 = 1

The path is: 1->5 = 6

--------------------------------

COMPLEXITY ANALYSIS :
As we can see there are three loops in a nested manner as:

1. k the outermost loop, running for n times => O(n)


2. Within that there is i loop, which also runs n times (considering every
vertex of the graph) => O(n^2)
3. Within that there is j loop, which is also running for n times (considering
all the adjacent vertices of vertex i) => O(n^3)

So the total complexity of the algorithm is max(n, n^2, n^3) => O(n^3)
ASSIGNMENT NO :9
PROBLEM STATEMENT :
Implement MST Problem using Kruskal’s algorithm. Mention the Compiler used
in your program. Analyze the complexity value of your algorithm

The compiler used here is GCC.

ALGORITHM:
Algorithm Kruskals(s)

Declare variables i, j, k, mincost = 0

// Initialize edge array with INF

For i from 1 to MAX2

edge[i][2] = INF

// Sorting the edges based on their weights

For i from 1 to n-1

For j from i+1 to n

If cost[i][j] is not INF

For k from count down to 1

If edge[k][2] > cost[i][j]

edge[k+1][2] = edge[k][2]

edge[k][2] = cost[i][j]

edge[k+1][0] = edge[k][0]

edge[k+1][1] = edge[k][1]
edge[k][0] = i

edge[k][1] = j

count = count + 1

// Constructing the minimum spanning tree

For i from 1 to count

If set[edge[i][0]] is not equal to set[edge[i][1]]

Call set_union(edge[i][0], edge[i][1])

Print edge[i][2]

mincost = mincost + edge[i][2]

Return mincost

Algorithm set_union(u, v)

Declare variable i

For i from 1 to n

If set[i] is equal to set[v] and i is not equal to v

set[i] = set[u]

set[v] = set[u]

Print "Edge", edgeno, ": ", u, " --> ", v, " = ", edge[i][2]

edgeno = edgeno + 1

}
PROGRAM CODE:
#include<stdio.h>

#define INF 9999

#define MAX 10

#define MAX2 2*MAX

int kruskals(int);

void set_union(int,int);

int cost[MAX][MAX],edge[2*MAX][3],set[10];

int n,count=1,edgeno=1;

void main()

int i,j;

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

scanf("%d",&n);

printf("\nEnter the cost matrix: ");

for(i=1;i<=n;i++)

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

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

if(cost[i][j]==0)

cost[i][j]=INF;

}
set[i]=i;//making individual set of all the vertices....

printf("\n\nThe Minimum cost of Spanning is: %d",kruskals(1));

int kruskals(int s)

int i,j,k,mincost=0;

for(i=1;i<MAX2;i++)

edge[i][2]=INF;

//Sorting the edges....

for(i=1;i<n;i++)

for(j=i+1;j<=n;j++)

if(cost[i][j]!=INF)

for(k=count;k>=1;k--)

if(edge[k][2]>cost[i][j])

edge[k+1][2]=edge[k][2];

edge[k][2]=cost[i][j];

edge[k+1][0]=edge[k][0];

edge[k+1][1]=edge[k][1];

edge[k][0]=i;
edge[k][1]=j;

count++;

for(i=1;i<=count;i++)

if(set[edge[i][0]]!=set[edge[i][1]])

{ //checking if vertex0 and vertex1 belongs to the same set....

set_union(edge[i][0],edge[i][1]);//if not making their


union....

printf("%d",edge[i][2]);//writing the edge cost....

mincost+=edge[i][2];

return mincost;

void set_union(int u,int v)

int i;

for(i=1;i<=n;i++)//making the union(set{u},set{v})....

if(set[i]==set[v] && i!=v)

set[i]=set[u];

set[v]=set[u];

printf("\nEdge%d: %d --> %d = ",edgeno++,u,v);//writing the edge....

}
RESULTS AND DISCUSSION:
Enter the number of vertices: 6

Enter the cost matrix: 0 8 1 5 0 0

805030

150564

505002

036006

004260

Edge1: 1 --> 3 = 1

Edge2: 4 --> 6 = 2

Edge3: 2 --> 5 = 3

Edge4: 3 --> 6 = 4

Edge5: 2 --> 3 = 5

The Minimum cost of Spanning is: 15

--------------------------------

COMPLEXITY ANALYSIS:
In this algorithm, if we ignore the sorting time needed to sort the edges,
then:

1. If there are m number of edges in the graph, then m number of edges


considered and thus the loop runs for m times => O(m)
2. Inside that, set_union function makes the union of the vertices of
associates to each edge set. So at most n vertices are considered
=> O(n)

Thus the final complexity is => O(mn)

Now if the sorting time is considered, and if we use simple insertion sorting
to sort the edges:

1. Since this is an undirected graph, so for sorting, we do not consider


the bi-directional nature of an edge to avoid repetition
2. Thus, for each consecutive vertex, there is a (n-1) adjacent vertex
choices to form an edge, so O(n!)
3. Now the inner k loop is used for sorting this new edge chosen in the
set of already considered edges, so if there are m edges in all, then the
final sorting complexity is => O(mxn!)
4. And the solving complexity is O(mn)

Thus final complexity would be => max(mn, mxn!) => O(mxn!)


ASSIGNMENT NO :13
PROBLEM STATEMENT :
Implement TSP using proper algorithm design technique. Mention the compiler
used in your program. Analyze the complexity value of your algorithm.

The Compiler used here is GCC.

ALGORITHM :
Function tsp(s) {

Curr s

While cities < n-1 {

min infinity

For each unvisited adjacent city i to curr {

If dist[curr][i] < min {

mindist[curr][i]

next i

visited[curr]=1

distance=distance + min

Print edge from curr to next with distance min

curr  next

cities=cities+1
}

Print edge from curr to s with distance dist[curr][s]

Return distance + dist[curr][s]

PROGRAM CODE :
#include<stdio.h>

#define INF 9999

#define MAX 10

int tsp(int);

int dist[MAX][MAX],visited[MAX],n;

void main()

int i,j,s;

printf("Enter the number of cities to visit: ");

scanf("%d",&n);

printf("Enter the distance matrix: ");

for(i=1;i<=n;i++)

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

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

if(dist[i][j]==0)

dist[i][j]=INF;
}

visited[i]=0;

printf("\nEnter the starting city: ");

scanf("%d",&s);

printf("\n\nThe minimum distance of traversal is: %d",tsp(s));

int tsp(int s)

int i,min,next,curr=s,distance=0,cities=0;

while(cities<n-1)

min=INF;

for(i=1;i<=n;i++)

if(dist[curr][i]<min && !visited[i])

min=dist[curr][i];

next=i;

visited[curr]=1;

distance+=min;

printf("\ncity %d --> city %d = %d",curr,next,min);


curr=next;

cities++;

printf("\ncity %d --> city %d = %d",curr,s,dist[curr][s]);

return distance+dist[curr][s];

RESULTS AND DISCUSSION :


Enter the number of cities to visit: 8

Enter the distance matrix: 0 5 0 6 0 4 0 7

50243000

02010000

64107000

03070064

40000030

00006302

70004020

Enter the starting city: 2

city 2 --> city 3 = 2

city 3 --> city 4 = 1

city 4 --> city 1 = 6


city 1 --> city 6 = 4

city 6 --> city 7 = 3

city 7 --> city 8 = 2

city 8 --> city 5 = 4

city 5 --> city 2 = 3

The minimum distance of traversal is: 25

--------------------------------

COMPLEXITY ANALYSIS :
In the tsp() function:

1. As the while is running for n times so the complexity is here O(n).


2. Then the for loop is running for n times, to consider all the adjacent
cities, so its complexity is O(n) as well. ss

Therefore, combining both of them the complexity hence is O(n^2).


ASSIGNMENT NO 17:
PROBLEM STATEMENT :
Implement 15-Puzzle problem. Mention the Compiler used in your program.
Analyze the complexity of your algorithm.

The compiler used here is GCC.

ALGORITHM :
1. Input the size of the puzzle grid (n) and the initial arrangement of the puzzle
(puzzle)

2. Check if the given puzzle arrangement is solvable{

If the puzzle is solvable, generate the goal state of the puzzle{

Solve the puzzle using A* search algorithm with a priority queue:

Create a priority queue (pq) to store puzzle states

Create the root node representing the initial state of the


puzzle

Calculate the cost of the root node based on the initial


arrangement and the goal state

Push the root node into the priority queue

While the priority queue is not empty{

Pop the node with the minimum priority (lowest cost


+ level) from the priority queue

If the popped node is the goal state, print the


solution and exit

Otherwise, expand the node:


- Generate child nodes by swapping the blank tile
with its neighbors

- Calculate the cost of each child node based on the


number of misplaced tiles

- Push the child nodes into the priority queue

Else{

Print "No solution found" if the priority queue becomes empty


without reaching the goal state

3. Function isSolvable():

Initialize inversions count to 0

Iterate over each tile in the puzzle:

If the tile is not blank:

Increment inversions count for each tile following it with a lower value

If the puzzle width is even:

Return true if the sum of inversions count and the row index of the blank
tile is even

Otherwise, return false

Else (if puzzle width is odd):

Return true if inversions count is even

Otherwise, return false

4. Function generateGoalState(n):
Create an empty 2D array goal with dimensions n x n

Initialize num to 1

Iterate over each cell in goal:

If num is equal to n * n:

Set the cell value to 0

Else:

Set the cell value to num

Increment num by 1

Return the goal array

5. Function createNode(puzzle, blankPos, newBlankPos, level, parent):

Create a new Node structure

Set the parent of the node to the parent parameter

Set the level of the node to the level parameter

Set the blank position of the node to the newBlankPos parameter

Copy the puzzle state from the puzzle parameter to the node's puzzle state

Swap the values of the blankPos and newBlankPos in the puzzle state

Return the created node

6. Function calculateCost(initial, goal):

Initialize count to 0

Iterate over each cell in the initial and goal arrays:

If the cell value in initial array is not zero and different from the
corresponding cell in goal:

Increment count

Return count
7. Function isSafe(x, y):

Return true if x and y are within the bounds of the puzzle grid

Otherwise, return false

8. Function push(pq, node):

Add the node to the nodes array of the priority queue

Increment the size of the priority queue

Bubble up the node to maintain the heap property

9. Function pop(pq):

Remove the minimum priority node from the priority queue

Decrement the size of the priority queue

Bubble down the root node to maintain the heap property

Return the removed node

10. Function printPuzzle(puzzle):

Iterate over each row in the puzzle:

Iterate over each cell in the row:

Print the value of the cell

Print a newline

Print an additional newline to separate puzzles

11. Function printPath(root):

If the root node is null:

Return

Recursively call printPath with the parent of the root node

Print the puzzle state of the root node


12. End

PROGRAM CODE :
#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

#define MAX 100

typedef struct {

int x, y;

} Point;

typedef struct Node {

int puzzle[MAX][MAX];

Point blankPos;

int cost;

int level;

struct Node* parent;

} Node;

typedef struct {

Node* nodes[MAX * MAX];

int size;

} PriorityQueue;

int isSolvable();

void solve(int initial[MAX][MAX], int blankX, int blankY, int goal[MAX]


[MAX]);

void NPuzzle();
int pos_BTile();

int calculateCost(int initial[MAX][MAX], int goal[MAX][MAX]);

Node* newNode(int puzzle[MAX][MAX], Point blankPos, Point


newBlankPos, int level, Node* parent);

void push(PriorityQueue* pq, Node* node);

Node* pop(PriorityQueue* pq);

void printPuzzle(int puzzle[MAX][MAX]);

void printPath(Node* root);

int isSafe(int x, int y);

int puzzle[MAX][MAX], flatten[MAX];

int n, row, column;

int main() {

int i, j;

printf("Enter the puzzle grid width: ");

scanf("%d", &n);

printf("Enter the puzzle (mark blank tile as 0): ");

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

for (j = 1; j <= n; j++) {

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

NPuzzle();

return 0;

}
void NPuzzle() {

if (isSolvable()) {

printf("\nThe given Puzzle Arrangement is Solvable\n");

int goal[MAX][MAX], num = 1;

int i, j;

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

for (j = 1; j <= n; j++) {

if (num == n * n) {

goal[i][j] = 0;

} else {

goal[i][j] = num++;

pos_BTile();

solve(puzzle, row, column, goal);

} else {

printf("\nThe given Puzzle Arrangement is not Solvable");

int isSolvable() {

int i, j, inv = 0, ind = 1;

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

for (j = 1; j <= n; j++) {


if (puzzle[i][j] != 0)

flatten[ind++] = puzzle[i][j];

for (i = 1; i < ind - 1; i++) {

for (j = i + 1; j < ind; j++) {

if (flatten[i] > flatten[j])

inv++;

if (n % 2 == 0) {

if ((inv + pos_BTile()) % 2 == 0)

return 0;

else

return 1;

} else {

if (inv % 2 == 0)

return 1;

else

return 0;

int pos_BTile() {

int i, j, pos = 0;
for (i = 1; i <= n; i++) {

for (j = 1; j <= n; j++) {

pos++;

if (puzzle[i][j] == 0) {

row = i;

column = j;

return pos;

return -1; // To avoid compiler warning, should never reach here

void solve(int initial[MAX][MAX], int blankX, int blankY, int goal[MAX]


[MAX]) {

PriorityQueue pq = { .size = 0 };

Point blankPos = { blankX, blankY };

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

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

push(&pq, root);

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

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

while (pq.size) {

Node* min = pop(&pq);

if (min->cost == 0) {
printf("Solution found in %d moves:\n", min->level);

printPath(min); // This will print all states from the initial to the
final state

printf("Final solved puzzle:\n");

printPuzzle(min->puzzle); // Print the final solved state explicitly

return;

int i;

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

int newX = min->blankPos.x + row[i];

int newY = min->blankPos.y + col[i];

if (isSafe(newX, newY)) {

Node* child = newNode(min->puzzle, min->blankPos, (Point)


{ newX, newY }, min->level + 1, min);

child->cost = calculateCost(child->puzzle, goal);

push(&pq, child);

Node* newNode(int puzzle[MAX][MAX], Point blankPos, Point


newBlankPos, int level, Node* parent) {
Node* node = (Node*)malloc(sizeof(Node));

node->parent = parent;

node->level = level;

node->blankPos = newBlankPos;

int i, j;

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

for (j = 1; j <= n; j++) {

node->puzzle[i][j] = puzzle[i][j];

int temp = node->puzzle[blankPos.x][blankPos.y];

node->puzzle[blankPos.x][blankPos.y] = node->puzzle[newBlankPos.x]
[newBlankPos.y];

node->puzzle[newBlankPos.x][newBlankPos.y] = temp;

return node;

int calculateCost(int initial[MAX][MAX], int goal[MAX][MAX]) {

int count = 0;

int i, j;

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

for (j = 1; j <= n; j++) {

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

count++;

}
}

return count;

void push(PriorityQueue* pq, Node* node) {

pq->nodes[pq->size++] = node;

int i = pq->size - 1;

while (i > 0 && (pq->nodes[i]->cost + pq->nodes[i]->level) < (pq-


>nodes[(i - 1) / 2]->cost + pq->nodes[(i - 1) / 2]->level)) {

Node* temp = pq->nodes[i];

pq->nodes[i] = pq->nodes[(i - 1) / 2];

pq->nodes[(i - 1) / 2] = temp;

i = (i - 1) / 2;

Node* pop(PriorityQueue* pq) {

Node* min = pq->nodes[0];

pq->nodes[0] = pq->nodes[--pq->size];

int i = 0;

while (2 * i + 1 < pq->size) {

int smallest = i;

if (2 * i + 1 < pq->size && (pq->nodes[2 * i + 1]->cost + pq->nodes[2 * i


+ 1]->level) < (pq->nodes[smallest]->cost + pq->nodes[smallest]->level)) {

smallest = 2 * i + 1;

}
if (2 * i + 2 < pq->size && (pq->nodes[2 * i + 2]->cost + pq->nodes[2 * i
+ 2]->level) < (pq->nodes[smallest]->cost + pq->nodes[smallest]->level)) {

smallest = 2 * i + 2;

if (smallest == i) break;

Node* temp = pq->nodes[i];

pq->nodes[i] = pq->nodes[smallest];

pq->nodes[smallest] = temp;

i = smallest;

return min;

void printPuzzle(int puzzle[MAX][MAX]) {

int i, j;

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

for (j = 1; j <= n; j++) {

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

printf("\n");

printf("\n");

void printPath(Node* root) {

if (root == NULL) return;


printPath(root->parent);

printPuzzle(root->puzzle);

int isSafe(int x, int y) {

return (x >= 1 && x <= n && y >= 1 && y <= n);

RESULTS AND DISCUSSION :


Enter the puzzle grid width: 4

Enter the puzzle (mark blank tile as 0): 1 2 3 4

5608

9 10 7 11

13 14 15 12

The given Puzzle Arrangement is Solvable

Solution found in 3 moves:

1 2 3 4

5 6 0 8

9 10 7 11

13 14 15 12

1 2 3 4

5 6 7 8

9 10 0 11

13 14 15 12
1 2 3 4

5 6 7 8

9 10 11 0

13 14 15 12

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 0

Final solved puzzle:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 0

COMPLEXITY ANALYSIS :
1. NPuzzle Function:
o isSolvable(): O(n^2) - The function computes the number of
inversions and checks if the puzzle is solvable based on its
dimensions and the number of inversions.
o pos_BTile(): O(n^2) - Determines the position of the blank tile
in the puzzle.
o solve(): O(b^d), where b is the branching factor (4 in this case)
and d is the depth of the solution.
o Creating the goal state: O(n^2)
2. Node Creation:
o newNode(): O(n^2) - Copies the puzzle state and swaps the
positions of tiles.
3. Priority Queue Operations:
o push(): O(log(N)) - Performs up-heap bubbling.
o pop(): O(log(N)) - Performs down-heap bubbling.
4. Printing:
o printPath(): O(d * n^2) - Prints the path from the initial state
to the final state.
5. Other Operations:
o calculateCost(): O(n^2) - Calculates the Manhattan distance
between the initial and goal states.
o isSafe(): O(1) - Checks if a given position is within the bounds
of the puzzle grid.

Overall, the time complexity is dominated by the solve() function, which has
a worst-case time complexity of O(b^d), where b is the branching factor (4 in
this case) and d is the depth of the solution. The space complexity mainly
depends on the priority queue size and the recursive depth of the solution path.

You might also like