0% found this document useful (0 votes)
31 views26 pages

Backtracking

The document outlines an experiment on backtracking algorithms implemented in C, focusing on problems such as the N-Queens problem, Sum of Subsets, M Coloring Problem, Hamiltonian Cycle, and 0/1 Knapsack Problem. It provides theoretical background, algorithms, time and space complexity analyses, and sample code for each problem. The document emphasizes the efficiency of backtracking in solving combinatorial problems while noting its potential exponential time complexity in the worst case.

Uploaded by

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

Backtracking

The document outlines an experiment on backtracking algorithms implemented in C, focusing on problems such as the N-Queens problem, Sum of Subsets, M Coloring Problem, Hamiltonian Cycle, and 0/1 Knapsack Problem. It provides theoretical background, algorithms, time and space complexity analyses, and sample code for each problem. The document emphasizes the efficiency of backtracking in solving combinatorial problems while noting its potential exponential time complexity in the worst case.

Uploaded by

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

Experiment No.

3: BACKTRACKING Date:18/04/2023

Aim:Write a C program to implement the following program using Dynamic programming


a. n queens problem
b. sum of subsets
c. m colouring problem
d. Hamiltonian cycle
e. 0/1 knapsack problem

THEORY:
Backtracking is a general algorithmic technique used to systematically search for solutions to
combinatorial problems. It is based on the idea of incrementally building a solution by
exploring all possible options and backtracking when a partial solution cannot be extended to
a complete solution.
The backtracking algorithm works as follows:
1. Start with an empty partial solution.
2. Choose the next element or option that can be added to the partial solution.
3. Check if the chosen element violates any constraints or conditions. If it does, discard it and
go back to step 2 (backtrack).
4. If the chosen element is valid, add it to the partial solution.
5. If the partial solution is complete (meets all the requirements), record it as a valid solution.
6. Recursively repeat steps 2-5 with the updated partial solution.
7. If all options have been explored, backtrack to the previous step and continue exploring
other options.
Backtracking is particularly useful for solving problems with a large search space where a
systematic exploration of all possible solutions is necessary. By eliminating invalid options
early in the process, backtracking reduces the number of unnecessary computations, making
it more efficient than exhaustive enumeration.
One of the key components of a backtracking algorithm is the decision-making process at
each step. The selection of the next option to consider can greatly affect the efficiency and
correctness of the algorithm. Careful consideration of constraints and heuristics can guide the
decision-making process and lead to more effective backtracking.
Backtracking is commonly used to solve various combinatorial problems, such as the n-
queens problem, Sudoku puzzles, graph coloring, subset sum problem, and many other
constraint satisfaction problems. It is a fundamental technique in algorithm design and is
often combined with other techniques, such as pruning or memoization, to further optimize
the search process.
However, it is important to note that backtracking can have an exponential time complexity
in the worst case, as it may need to explore all possible combinations. In such cases,
additional optimizations or alternative algorithms may be required to improve the
performance.

RollNo. 211105036 |Page


a) N QUEENS PROBLEM
Date:18/04/2023
Problem Statement:

Write a c program to implement N-QUEENS algorithm for 4 queens .

Algorithm:

TIME AND SPACE COMPLEXITY :

Time complexity :
The time complexity of the N-Queens problem when solved using backtracking depends on
the specific implementation and the size of the chessboard (N).

In the N-Queens problem, the goal is to place N queens on an N×N chessboard in such a way
that no two queens threaten each other. Backtracking is a common approach to solve this

RollNo. 211105036 |Page


problem, where the algorithm explores different configurations of queen placements,
backtracking when conflicts are encountered.

In the worst case, the backtracking algorithm for the N-Queens problem has an exponential
time complexity. This is because the algorithm explores all possible configurations of queen
placements, resulting in a branching factor of N at each level of the recursion. The worst-
case scenario occurs when there are no restrictions on the placements or symmetries in the
chessboard.

Therefore, the worst-case time complexity of the backtracking algorithm for the N-Queens
problem is O(N!), where N is the size of the chessboard. This exponential time complexity
arises from the exponential growth in the number of recursive calls and the branching factor
at each level.

SPACE COMPLEXITY :
The space complexity of the N-Queens problem when solved using backtracking depends on
the specific implementation and how the algorithm stores and tracks data during the
recursion.

In a basic backtracking implementation, the space complexity is determined by the maximum


depth of the recursion, which corresponds to the number of rows or queens in the chessboard
(N). This is because each recursive call creates a new stack frame, which includes local
variables, parameters, and return addresses.

Additionally, the algorithm may use additional space to store the current state of the queen
placements and track the valid positions. The space required for this state tracking typically
grows linearly with the number of queens or the size of the chessboard, so it contributes
O(N) space complexity.

Therefore, the overall space complexity of the basic backtracking implementation for the N-
Queens problem is O(N) in the worst case.

CODE :
/*code for N queen’s problem*/

#include <stdio.h>
#define N 20
int M[N],i,j;

int Place(int k, int i)


{
for ( j = 0; j < k; j++)
{
if (M[j] == i)
return 0;
else if (abs(i - M[j]) == abs(k - j))
return 0;

RollNo. 211105036 |Page


}
return 1;
}

void print(int n)
{int j;
printf("\n\n");
for ( i = 1; i <= n; i++)
{
printf("\t%d", i);
}
for ( i = 1; i <= n; i++)
{
printf("\n\n%d", i);
for (j = 1; j <= n; j++)
{
if (M[i] == j)
printf("\tQ");
else
printf("\t_");
}
};
printf("\n\n");
}

void nqueen(int k, int n)


{int i;
for ( i= 1; i<= n; i++)
{
if (Place(k, i))
{
M[k] = i;
if (k == n)
{
print(n);
return;
}
else
nqueen(k + 1, n);
}
}
}

int main()
{
int n;
printf("Enter the size(n):");
scanf("%d", &n);
nqueen(1, n);
return 0;
}

OUTPUT :

C:\Users\Nidhi Shanbhag \Downloads\madf CODES\NQueens_problem.exe


Enter the size(n):4

RollNo. 211105036 |Page


1 2 3 4

1 _ Q _ _

2 _ _ _ Q

3 Q _ _ _

4 _ _ Q _

1 2 3 4

1 _ _ Q _

2 Q _ _ _

3 _ _ _ Q

4 _ Q _ _

--------------------------------
Process exited after 1.314 seconds with return value 0
Press any key to continue . . .

RollNo. 211105036 |Page


b) SUM OF SUBSETS
Date:18/04/2023
Problem Statement:

Write a c program to implement SUM OF SUBSETS algorithm for the following problem:
Given ‘n’ weights, find the combinations of these weights such that the total weight of the
subset equal to ‘m’ (where n and m are given)

W = {5, 10, 12, 13, 15, 18} m = 30

Algorithm

Time and space complexity :

Time complexity :
The time complexity of the Subset Sum problem depends on the specific algorithm used to
solve it. There are several approaches to solving Subset Sum, and the time complexity can
vary depending on the chosen method.

RollNo. 211105036 |Page


The backtracking approach explores different combinations of elements to construct subsets
and backtracks when the sum exceeds the target or all elements have been considered. In the
worst case, the backtracking approach has an exponential time complexity of O(2^n), where
n is the number of elements in the input set. However, the actual running time can be
improved with pruning techniques and heuristics.
It's important to note that the Subset Sum problem is NP-complete, which means that no
known efficient polynomial-time algorithm exists for solving it in the general case.
Therefore, the time complexity is typically exponential, unless there are specific constraints
or structures in the input that allow for more efficient solutions.
Space complexity :
The space complexity of the Subset Sum problem when solved using backtracking depends
on the specific implementation and how the algorithm stores and tracks data during the
recursion.
In a basic backtracking implementation, the space complexity is determined by the maximum
depth of the recursion, which corresponds to the number of elements in the input set. This is
because each recursive call creates a new stack frame, which includes local variables,
parameters, and return addresses.
Additionally, the algorithm may use additional space to store the current state of the subset
being constructed during the recursion. The space required for this subset tracking typically
grows linearly with the number of elements, so it contributes O(n) space complexity, where n
is the number of elements in the input set.
Therefore, the overall space complexity of the basic backtracking implementation for the
Subset Sum problem is O(n) in the worst case.

Code

/*code for sum of subsets Algorithm */


#include <stdio.h>
#define N 20

int n, m,i;

void print(int w[N], int k, int x[N])


{
printf("( ");
for ( i = 1; i <= k; i++)
printf("%d, ", x[i]);
printf(") ie. sum of the subset ( ");
for (i = 1; i <= k; i++)
{
if (x[i] == 1)
printf("%d, ", w[i]);
}
printf(")\n");
}

void sumofsub(int s, int k, int r, int w[], int x[])


{
if (k > n)
return;
x[k] = 1;

RollNo. 211105036 |Page


if (s + w[k] == m)
print(w, k, x);
else if ((s + w[k] + w[k + 1]) <= m)
sumofsub(s + w[k], k + 1, r, w, x);
if (((s + r - w[k]) >= m) && (s + w[k + 1] <= m))
{
x[k] = 0;
sumofsub(s, k + 1, r, w, x);
}
}

int main()
{
int r = 0;

printf("Enter the no. of elements: ");


scanf("%d", &n);
int w[n + 1], x[n + 1];

printf("Enter the elements:\n");


for ( i = 1; i <= n; i++)
{
x[i] = 0;
scanf("%d", &w[i]);
r += w[i];
}

printf("Enter max weight: ");


scanf("%d", &m);
sumofsub(0, 1, r, w, x);
return 0;
}

OUTPUT :
C:\Users\ Nidhi Shanbhag \Downloads\madf CODES\sumofsubsets.exe

Enter the number of elements: 6


Enter the elements
5
10
12
13
15
18
Enter max weight: 30
( 1, 1, 0, 0, 1, ) ie. sum of the subset ( 5, 10, 15, )
( 1, 0, 1, 1, ) ie. sum of the subset ( 5, 12, 13, )
( 0, 0, 1, 0, 0, 1, ) ie. sum of the subset ( 12, 18, )
--------------------------------
Process exited after 6.7 seconds with return value 0
Press any key to continue . . .

RollNo. 211105036 |Page


c) M colouring problem
Date:28/04/2023
Problem Statement:

Write a c program to implement M-COLOURING ALGORITHM on following problem:

Given below are the time slots of taxis. Only one taxi is available for the service at a time.
Find the most efficient way to schedule the appointment:

10

ALGORITHM :

RollNo. 211105036 |Page


Time and space complexity :

Time complexity :
The time complexity of the m-coloring problem when solved using backtracking depends on
the specific implementation and characteristics of the graph being considered.
In the m-coloring problem, the goal is to color the vertices of a graph with at most m colors,
such that no adjacent vertices have the same color. The backtracking algorithm explores
different color assignments for each vertex and backtracks when it encounters a conflict.
In the worst case, the backtracking algorithm for the m-coloring problem has an exponential
time complexity. This is because the algorithm explores all possible color assignments for
each vertex, resulting in a branching factor of m at each level of the recursion. The worst-
case scenario occurs when every vertex has m possible colors to choose from.

RollNo. 211105036 |Page


Therefore, the worst-case time complexity of the backtracking algorithm for the m-coloring
problem is O(m^n), where n is the number of vertices in the graph. This exponential time
complexity arises from the exponential growth in the number of recursive calls and the
branching factor at each level.
Space complexity :
The space complexity of the m-coloring problem when solved using backtracking depends on
the specific implementation and how the algorithm stores and tracks data during the
recursion.
In a basic backtracking implementation, the space complexity is determined by the maximum
depth of the recursion, which corresponds to the number of vertices in the graph. This is
because each recursive call creates a new stack frame, which includes local variables,
parameters, and return addresses.
Additionally, the algorithm may use additional space to store the current state of the coloring
and track the colors assigned to each vertex. The space required for this coloring state
tracking typically grows linearly with the number of vertices, so it contributes O(n) space
complexity.
Therefore, the overall space complexity of the basic backtracking implementation for the m-
coloring problem is O(n) in the worst case.

Code:

/*code for M colouring Algorithm */

#include <stdio.h>
#define N 20

int G[N][N], count = 0,i,j;

int c[7] = {'V', 'I', 'B', 'G', 'Y', 'O', 'R'};

void nextval(int x[N], int nodes, int colors, int k)


{
do
{
x[k] = (x[k] + 1) % (colors + 1);
if (!x[k])
return;
int j;
for (j = 1; j <= nodes; j++)
{
if ((G[k][j] != 0) && (x[k] == x[j]))
break;
}
if (j == nodes + 1)
return;
} while (1);
}

void show(int x[N], int nodes)


{
printf("%d.\t", ++count);

RollNo. 211105036 |Page


for (i = 1; i <= nodes; i++)
printf("%c ", c[x[i]]);
printf("\n");
}

void color(int x[N], int nodes, int colors, int k)


{
do
{
nextval(x, nodes, colors, k);
if (!x[k])
return;
if (k == nodes)
show(x, nodes);
else
color(x, nodes, colors, k + 1);

} while (1);
}

int main()
{
int nodes, edges, colors, o, d, x[N];
printf("Enter the number of nodes: "), scanf("%d",&nodes);

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


for ( j = 1; j <= nodes; j++)
G[i][j] = 0;

printf("Enter the number of edges: "),scanf("%d",&edges) ;

printf("Enter origin and destination:\n");


for (i = 0; i < edges; i++)
scanf("%d",&o) ,scanf("%d",&d), G[o][d] = G[d][o] = 1;

printf("Enter the number of colors: "), scanf("%d",&colors);


for ( i = 1; i <= nodes; i++)
x[i] = 0;
printf("\n\n");
printf("The following are the possible ways to color the nodes of
the graph:");
printf("\n\n");
color(x, nodes, colors, 1);
return 0;
}

OUTPUT :

C:\Users\ Nidhi Shanbhag \Downloads\madf CODES\mcolouring.exe


Enter the number of nodes: 10 56
Enter the number of edges: 10 57
Enter origin and destination 67
12 89
13 9 10
14 Enter the number of colors: 3
23
34

RollNo. 211105036 |Page


The possible ways to color the nodes of 57. I BGBGIBGIB
the graph are 58. I BGBGIBGIG
59. I BGBGIBGBI
1. I BGBIBGIBI 60. I BGBGIBGBG
2. I BGBIBGIBG 61. I BGBGBIIBI
3. I BGBIBGIGI 62. I BGBGBIIBG
4. I BGBIBGIGB 63. I BGBGBIIGI
5. I BGBIBGBIB 64. I BGBGBIIGB
6. I BGBIBGBIG 65. I BGBGBIBIB
7. I BGBIBGBGI 66. I BGBGBIBIG
8. I BGBIBGBGB 67. I BGBGBIBGI
9. I BGBIBGGIB 68. I BGBGBIBGB
10. IBGBIBGGIG 69. I BGBGBIGIB
11. IBGBIBGGBI 70. I BGBGBIGIG
12. IBGBIBGGBG 71. I BGBGBIGBI
13. IBGBIGBIBI 72. I BGBGBIGBG
14. IBGBIGBIBG 73. I GBGIBGIBI
15. IBGBIGBIGI 74. I GBGIBGIBG
16. IBGBIGBIGB 75. I GBGIBGIGI
17. IBGBIGBBIB 76. I GBGIBGIGB
18. IBGBIGBBIG 77. I GBGIBGBIB
19. IBGBIGBBGI 78. I GBGIBGBIG
20. IBGBIGBBGB 79. I GBGIBGBGI
21. IBGBIGBGIB 80. I GBGIBGBGB
22. IBGBIGBGIG 81. I GBGIBGGIB
23. IBGBIGBGBI 82. I GBGIBGGIG
24. IBGBIGBGBG 83. I GBGIBGGBI
25. IBGBBIGIBI 84. I GBGIBGGBG
26. IBGBBIGIBG 85. I GBGIGBIBI
27. IBGBBIGIGI 86. I GBGIGBIBG
28. IBGBBIGIGB 87. I GBGIGBIGI
29. IBGBBIGBIB 88. I GBGIGBIGB
30. IBGBBIGBIG 89. I GBGIGBBIB
31. IBGBBIGBGI 90. I GBGIGBBIG
32. IBGBBIGBGB 91. I GBGIGBBGI
33. IBGBBIGGIB 92. I GBGIGBBGB
34. IBGBBIGGIG 93. I GBGIGBGIB
35. IBGBBIGGBI 94. I GBGIGBGIG
36. IBGBBIGGBG 95. I GBGIGBGBI
37. IBGBBGIIBI 96. I GBGIGBGBG
38. IBGBBGIIBG 97. I GBGBIGIBI
39. IBGBBGIIGI 98. I GBGBIGIBG
40. IBGBBGIIGB 99. I GBGBIGIGI
41. IBGBBGIBIB 100. IGBGBIGIGB
42. IBGBBGIBIG 101. IGBGBIGBIB
43. IBGBBGIBGI 102. IGBGBIGBIG
44. IBGBBGIBGB 103. IGBGBIGBGI
45. IBGBBGIGIB 104. IGBGBIGBGB
46. IBGBBGIGIG 105. IGBGBIGGIB
47. IBGBBGIGBI 106. IGBGBIGGIG
48. IBGBBGIGBG 107. IGBGBIGGBI
49. IBGBGIBIBI 108. IGBGBIGGBG
50. IBGBGIBIBG 109. IGBGBGIIBI
51. IBGBGIBIGI 110. IGBGBGIIBG
52. IBGBGIBIGB 111. IGBGBGIIGI
53. IBGBGIBBIB 112. IGBGBGIIGB
54. IBGBGIBBIG 113. IGBGBGIBIB
55. IBGBGIBBGI 114. IGBGBGIBIG
56. IBGBGIBBGB 115. IGBGBGIBGI

RollNo. 211105036 |Page


116. IGB GBGIBGB 175. B IG IBIGBGI
117. IGB GBGIGIB 176. B IG IBIGBGB
118. IGB GBGIGIG 177. B IG IBIGGIB
119. IGB GBGIGBI 178. B IG IBIGGIG
120. IGB GBGIGBG 179. B IG IBIGGBI
121. IGB GGIBIBI 180. B IG IBIGGBG
122. IGB GGIBIBG 181. B IG IBGIIBI
123. IGB GGIBIGI 182. B IG IBGIIBG
124. IGB GGIBIGB 183. B IG IBGIIGI
125. IGB GGIBBIB 184. B IG IBGIIGB
126. IGB GGIBBIG 185. B IG IBGIBIB
127. IGB GGIBBGI 186. B IG IBGIBIG
128. IGB GGIBBGB 187. B IG IBGIBGI
129. IGB GGIBGIB 188. B IG IBGIBGB
130. IGB GGIBGIG 189. B IG IBGIGIB
131. IGB GGIBGBI 190. B IG IBGIGIG
132. IGB GGIBGBG 191. B IG IBGIGBI
133. IGB GGBIIBI 192. B IG IBGIGBG
134. IGB GGBIIBG 193. B IG IGIBIBI
135. IGB GGBIIGI 194. B IG IGIBIBG
136. IGB GGBIIGB 195. B IG IGIBIGI
137. IGB GGBIBIB 196. B IG IGIBIGB
138. IGB GGBIBIG 197. B IG IGIBBIB
139. IGB GGBIBGI 198. B IG IGIBBIG
140. IGB GGBIBGB 199. B IG IGIBBGI
141. IGB GGBIGIB 200. B IG IGIBBGB
142. IGB GGBIGIG 201. B IG IGIBGIB
143. IGB GGBIGBI 202. B IG IGIBGIG
144. IGB GGBIGBG 203. B IG IGIBGBI
145. BIG IIBGIBI 204. B IG IGIBGBG
146. BIG IIBGIBG 205. B IG IGBIIBI
147. BIG IIBGIGI 206. B IG IGBIIBG
148. BIG IIBGIGB 207. B IG IGBIIGI
149. BIG IIBGBIB 208. B IG IGBIIGB
150. BIG IIBGBIG 209. B IG IGBIBIB
151. BIG IIBGBGI 210. B IG IGBIBIG
152. BIG IIBGBGB 211. B IG IGBIBGI
153. BIG IIBGGIB 212. B IG IGBIBGB
154. BIG IIBGGIG 213. B IG IGBIGIB
155. BIG IIBGGBI 214. B IG IGBIGIG
156. BIG IIBGGBG 215. B IG IGBIGBI
157. BIG IIGBIBI 216. B IG IGBIGBG
158. BIG IIGBIBG 217. B GI GIBGIBI
159. BIG IIGBIGI 218. B GI GIBGIBG
160. BIG IIGBIGB 219. B GI GIBGIGI
161. BIG IIGBBIB 220. B GI GIBGIGB
162. BIG IIGBBIG 221. B GI GIBGBIB
163. BIG IIGBBGI 222. B GI GIBGBIG
164. BIG IIGBBGB 223. B GI GIBGBGI
165. BIG IIGBGIB 224. B GI GIBGBGB
166. BIG IIGBGIG 225. B GI GIBGGIB
167. BIG IIGBGBI 226. B GI GIBGGIG
168. BIG IIGBGBG 227. B GI GIBGGBI
169. BIG IBIGIBI 228. B GI GIBGGBG
170. BIG IBIGIBG 229. B GI GIGBIBI
171. BIG IBIGIGI 230. B GI GIGBIBG
172. BIG IBIGIGB 231. B GI GIGBIGI
173. BIG IBIGBIB 232. B GI GIGBIGB
174. BIG IBIGBIG 233. B GI GIGBBIB

RollNo. 211105036 |Page


234. BGI GIGBBIG 293. G I B I IBG BIB
235. BGI GIGBBGI 294. G I B I IBG BIG
236. BGI GIGBBGB 295. G I B I IBG BGI
237. BGI GIGBGIB 296. G I B I IBG BGB
238. BGI GIGBGIG 297. G I B I IBG GIB
239. BGI GIGBGBI 298. G I B I IBG GIG
240. BGI GIGBGBG 299. G I B I IBG GBI
241. BGI GBIGIBI 300. G I B I IBG GBG
242. BGI GBIGIBG 301. G I B I IGB IBI
243. BGI GBIGIGI 302. G I B I IGB IBG
244. BGI GBIGIGB 303. G I B I IGB IGI
245. BGI GBIGBIB 304. G I B I IGB IGB
246. BGI GBIGBIG 305. G I B I IGB BIB
247. BGI GBIGBGI 306. G I B I IGB BIG
248. BGI GBIGBGB 307. G I B I IGB BGI
249. BGI GBIGGIB 308. G I B I IGB BGB
250. BGI GBIGGIG 309. G I B I IGB GIB
251. BGI GBIGGBI 310. G I B I IGB GIG
252. BGI GBIGGBG 311. G I B I IGB GBI
253. BGI GBGIIBI 312. G I B I IGB GBG
254. BGI GBGIIBG 313. G I B I BIG IBI
255. BGI GBGIIGI 314. G I B I BIG IBG
256. BGI GBGIIGB 315. G I B I BIG IGI
257. BGI GBGIBIB 316. G I B I BIG IGB
258. BGI GBGIBIG 317. G I B I BIG BIB
259. BGI GBGIBGI 318. G I B I BIG BIG
260. BGI GBGIBGB 319. G I B I BIG BGI
261. BGI GBGIGIB 320. G I B I BIG BGB
262. BGI GBGIGIG 321. G I B I BIG GIB
263. BGI GBGIGBI 322. G I B I BIG GIG
264. BGI GBGIGBG 323. G I B I BIG GBI
265. BGI GGIBIBI 324. G I B I BIG GBG
266. BGI GGIBIBG 325. G I B I BGI IBI
267. BGI GGIBIGI 326. G I B I BGI IBG
268. BGI GGIBIGB 327. G I B I BGI IGI
269. BGI GGIBBIB 328. G I B I BGI IGB
270. BGI GGIBBIG 329. G I B I BGI BIB
271. BGI GGIBBGI 330. G I B I BGI BIG
272. BGI GGIBBGB 331. G I B I BGI BGI
273. BGI GGIBGIB 332. G I B I BGI BGB
274. BGI GGIBGIG 333. G I B I BGI GIB
275. BGI GGIBGBI 334. G I B I BGI GIG
276. BGI GGIBGBG 335. G I B I BGI GBI
277. BGI GGBIIBI 336. G I B I BGI GBG
278. BGI GGBIIBG 337. G I B I GIB IBI
279. BGI GGBIIGI 338. G I B I GIB IBG
280. BGI GGBIIGB 339. G I B I GIB IGI
281. BGI GGBIBIB 340. G I B I GIB IGB
282. BGI GGBIBIG 341. G I B I GIB BIB
283. BGI GGBIBGI 342. G I B I GIB BIG
284. BGI GGBIBGB 343. G I B I GIB BGI
285. BGI GGBIGIB 344. G I B I GIB BGB
286. BGI GGBIGIG 345. G I B I GIB GIB
287. BGI GGBIGBI 346. G I B I GIB GIG
288. BGI GGBIGBG 347. G I B I GIB GBI
289. GIB IIBGIBI 348. G I B I GIB GBG
290. GIB IIBGIBG 349. G I B I GBI IBI
291. GIB IIBGIGI 350. G I B I GBI IBG
292. GIB IIBGIGB 351. G I B I GBI IGI

RollNo. 211105036 |Page


352. G IB IGBIIGB 399. G B I B BGI IGI
353. G IB IGBIBIB 400. G B I B BGI IGB
354. G IB IGBIBIG 401. G B I B BGI BIB
355. G IB IGBIBGI 402. G B I B BGI BIG
356. G IB IGBIBGB 403. G B I B BGI BGI
357. G IB IGBIGIB 404. G B I B BGI BGB
358. G IB IGBIGIG 405. G B I B BGI GIB
359. G IB IGBIGBI 406. G B I B BGI GIG
360. G IB IGBIGBG 407. G B I B BGI GBI
361. G BI BIBGIBI 408. G B I B BGI GBG
362. G BI BIBGIBG 409. G B I B GIB IBI
363. G BI BIBGIGI 410. G B I B GIB IBG
364. G BI BIBGIGB 411. G B I B GIB IGI
365. G BI BIBGBIB 412. G B I B GIB IGB
366. G BI BIBGBIG 413. G B I B GIB BIB
367. G BI BIBGBGI 414. G B I B GIB BIG
368. G BI BIBGBGB 415. G B I B GIB BGI
369. G BI BIBGGIB 416. G B I B GIB BGB
370. G BI BIBGGIG 417. G B I B GIB GIB
371. G BI BIBGGBI 418. G B I B GIB GIG
372. G BI BIBGGBG 419. G B I B GIB GBI
373. G BI BIGBIBI 420. G B I B GIB GBG
374. G BI BIGBIBG 421. G B I B GBI IBI
375. G BI BIGBIGI 422. G B I B GBI IBG
376. G BI BIGBIGB 423. G B I B GBI IGI
377. G BI BIGBBIB 424. G B I B GBI IGB
378. G BI BIGBBIG 425. G B I B GBI BIB
379. G BI BIGBBGI 426. G B I B GBI BIG
380. G BI BIGBBGB 427. G B I B GBI BGI
381. G BI BIGBGIB 428. G B I B GBI BGB
382. G BI BIGBGIG 429. G B I B GBI GIB
383. G BI BIGBGBI 430. G B I B GBI GIG
384. G BI BIGBGBG 431. G B I B GBI GBI
385. G BI BBIGIBI 432. G B I B GBI GBG
386. G BI BBIGIBG
387. G BI BBIGIGI --------------------------------
388. G BI BBIGIGB Process exited after 6.661 seconds with
389. G BI BBIGBIB return value 0
390. G BI BBIGBIG Press any key to continue . . .
391. G BI BBIGBGI
392. G BI BBIGBGB
393. G BI BBIGGIB
394. G BI BBIGGIG
395. G BI BBIGGBI
396. G BI BBIGGBG
397. G BI BBGIIBI
398. G BI BBGIIBG

d) HAMILTONIAN CYCLE
Date:28/04/2023
RollNo. 211105036 |Page
Problem Statement:
Write a c program to calculate all possible Hamiltonian cycle in the following graph:

Algorithm:

RollNo. 211105036 |Page


TIME AND SPACE COMPLEXITY :

Time complexity :
The time complexity of the Hamiltonian cycle problem when solved using backtracking
depends on the specific implementation and characteristics of the graph being considered.
In the worst case, the backtracking algorithm for finding a Hamiltonian cycle has an
exponential time complexity. This is because the algorithm explores all possible
permutations of the vertices to construct a cycle and checks whether each permutation
satisfies the conditions of a Hamiltonian cycle.
The number of possible permutations of n vertices is n!, which grows factorially with the
number of vertices. Therefore, the worst-case time complexity of the backtracking algorithm
for finding a Hamiltonian cycle is O(n!).

Space complexity ;
The space complexity of the Hamiltonian cycle problem when solved using backtracking depends on
the specific implementation and how the algorithm stores and tracks data during the recursion.
In a basic backtracking implementation, the space complexity is determined by the maximum depth
of the recursion, which corresponds to the number of vertices in the graph. This is because each
recursive call creates a new stack frame, which includes local variables, parameters, and return
addresses.
Additionally, the algorithm may use additional space to maintain the current path or cycle being
constructed during the recursion. The space required for this path tracking typically grows linearly
with the number of vertices, so it contributes O(n) space complexity.
Therefore, the overall space complexity of the basic backtracking implementation for the
Hamiltonian cycle problem is O(n) in the worst case.

Code

RollNo. 211105036 |Page


/*code for Hamiltonian cycles Algorithm */
#include <stdio.h>
#define N 100

int G[N][N], count = 0,i,j;

void nextvalue(int x[N], int nodes, int k)


{
do
{
x[k] = (x[k] + 1) % (nodes + 1);
if (!x[k])
return;
if (G[x[k - 1]][x[k]] != 0)
{
int j;
for (j = 1; j <= k - 1; j++)
if (x[j] == x[k])
break;
if (j == k)
if ((k < nodes) || ((k == nodes && G[x[nodes]][x[1]] !=
0)))
return;
}
} while (1);
}

void show(int x[N], int nodes)


{
printf("%d.\t", ++count);
for (i = 1; i <= nodes; i++)
printf("%d -> ", x[i]);
printf("%d", x[1]);
printf("\n");
}

void hamiltonian(int x[N], int nodes, int k)


{
do
{
nextvalue(x, nodes, k);
if (!x[k])
return;
if (k == nodes)
show(x, nodes);
else
hamiltonian(x, nodes, k + 1);
} while (1);
}

int main()
{
int nodes, edges, o, d, x[N];
printf("Enter the number of nodes: "), scanf("%d",&nodes);

RollNo. 211105036 |Page


for (i = 1; i <= nodes; i++)
for ( j = 1; j <= nodes; j++)
G[i][j] = 0;

printf("Enter the number of edges: "), scanf("%d",&edges);

printf("Enter origin and destination\n");


for (i = 0; i < edges; i++)
scanf("%d %d",&o,&d), G[o][d] = G[d][o] = 1;
int k;
printf("Enter the starting vertex: "),scanf("%d",&k);
x[1] = k;
for (i = 2; i <= nodes; i++)
x[i] = 0;
printf("\n\n");
printf("The Hamiltonian Cycles starting from node %d are:", k);
printf("\n\n");
hamiltonian(x, nodes, 2);
return 0;
}

OUTPUT :

C:\Users\ Nidhi Shanbhag \Downloads\madf CODES\hamiltonian.exe

Enter the number of nodes: 6


Enter the number of edges: 10
Enter origin and destination
12
23
13
14
43
45
25
35
46
56
Enter the starting vertex: 1

The Hamiltonian Cycles starting from node 1 are:

1. 1 -> 2 -> 3 -> 5 -> 6 -> 4 -> 1


2. 1 -> 2 -> 5 -> 6 -> 4 -> 3 -> 1
3. 1 -> 3 -> 2 -> 5 -> 6 -> 4 -> 1
4. 1 -> 3 -> 4 -> 6 -> 5 -> 2 -> 1
5. 1 -> 4 -> 6 -> 5 -> 2 -> 3 -> 1
6. 1 -> 4 -> 6 -> 5 -> 3 -> 2 -> 1

--------------------------------
Process exited after 47.15 seconds with return value 0

RollNo. 211105036 |Page


Press any key to continue . . .

e) 0/1 KNAPSACK PROBLEM


Date:02/05/2023
Problem Statement:
Write a c program to implement 0/1 knapsack using dynamic programming on the following knapsack :

N=4

M=8

p1,p2,p3,p4={3,5,6,10}

w1,w2,w3,w4}={2,3,4,5,}

Algorithm;

RollNo. 211105036 |Page


Time and space complexity :
Time complexity ;
The time complexity of the 0/1 knapsack problem when solved using backtracking depends
on the specific implementation. In the worst case, the time complexity is exponential,
O(2^n), where n is the number of items to choose from.
In the backtracking approach, the algorithm explores all possible combinations of items by
recursively considering whether each item should be included in the knapsack or not. This
results in a binary tree with a depth of n, where each node represents an item and has two
branches (representing whether the item is included or excluded).
Since there are two choices at each level of the recursion (to include or exclude an item), the
number of nodes in the tree is 2^n. The algorithm visits each node to evaluate the
corresponding combination, resulting in a time complexity of O(2^n) in the worst case.
Space complexity :
The space complexity of the 0/1 knapsack problem when solved using backtracking depends
on the specific implementation and how the algorithm stores and tracks data during the
recursion.
In a basic backtracking implementation, the space complexity is determined by the maximum
depth of the recursion, which is equal to the number of items, n. This is because each
recursive call creates a new stack frame, which includes local variables, parameters, and
return addresses.
Additionally, the algorithm may use additional space to store the current state of the
knapsack and track the best solution found so far. The space required for this state tracking
typically grows linearly with the number of items, so it contributes O(n) space complexity.
Code

RollNo. 211105036 |Page


/*code for 0/1 knapsack Algorithm */
#include<stdio.h>
#include<stdlib.h>
int p[100], w[100];
int x[100],y[100];
int m, n,fp=0,fw=0;
void knapsack(int,int,int);
float bound(int,int,int);
void knapsack(int k,int cp,int cw)
{
if(cw+w[k]<=m)
{
y[k]=1;
if(k<n)knapsack(k+1,cp+p[k],cw+w[k]);
if((cp+p[k]>fp) && k==n)
{
fp=cp+p[k];
fw=cw+w[k];
for(int j=1;j<=k;j++)x[j]=y[j];
}
}
if(bound(cp,cw,k)>=fp)
{
y[k]=0;
if(k<n)
knapsack(k+1,cp,cw);
if((cp>fp)&& k==n)
{
fp=cp;
fw=cw;
for(int j=1;j<=k;j++)
x[j]=y[j];
}
}
}
float bound(int cp,int cw,int k)
{
int b=cp,c=cw;
for(int i=k+1;i<=n;i++)
{
c=c+w[i];
if(c<m)
b=b+p[i];
else
return b+(1-(c-m)/(float)w[i])*p[i];

}
return b;
}
int main()
{
int profit=0, weight=0;
printf("Enter number of objects[n]: ");
scanf("%d",&n);
printf("Enter sack size[m]: ");

RollNo. 211105036 |Page


scanf("%d",&m);
printf("\nEnter profits :\n");
for(int i=1; i<=n; i++)
{
printf("P[%d]: ",i);
scanf("%d",&p[i]);
}
printf("\nEnter weights : \n");
for(int i=1; i<=n; i++)
{
printf("W[%d]: ",i);
scanf("%d",&w[i]);
x[i] = 0;
}
knapsack(0,0,1);
printf("\nSolution Vector: (");
for(int i=1; i<=n; i++)
{
profit+=p[i]*x[i];
weight+=w[i]*x[i];
printf("%d",x[i]);
if(i<n)
{
printf(",");
}
}
printf(")\n");
printf("\nMAX Profit = %d \n",profit);
printf("Weight Occupied = %d ",weight);

return 0;
}
OUTPUT :
C:\Users\ Nidhi Shanbhag \Downloads\madf CODES\knapsack_bt.exe
Enter number of objects[n]: 4
Enter sack size[m]: 8
Enter profits :
P[1]: 3
P[2]: 5
P[3]: 6
P[4]: 10

Enter weights :
W[1]: 2
W[2]: 3
W[3]: 4
W[4]: 5

Solution Vector: (1,0,0,1)

MAX Profit = 13
Weight Occupied = 7

RollNo. 211105036 |Page


--------------------------------
Process exited after 19.19 seconds with return value 0
Press any key to continue . . .

CONCLUSION:
The Backtracking method was studied.

The programs for:

(a) N-QUEENS PROBLEM

(b) SUM OF SUBSETS

(c) M-COLOURING PROBLEM

(d) HAMILTONIAN CYCLE

(e) 0/1 KNAPSACK PROBLEM

were studied and implemented successfully

RollNo. 211105036 |Page


RollNo. 211105036 |Page

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy