DM Assignment 1 Answer
DM Assignment 1 Answer
Ramapuram Campus
Department of Mathematics
Assignment
21MAB302T–Discrete Mathematics
1. Write a C Program to Find the Transitive Closure of a Graph using Warshall’s Algorithm.
Ans
1. #include<stdio.h>
2. #include<conio.h>
3. #include<math.h>
4. int max(int, int);
5. void warshal(int p[10][10], int n) {
6. int i, j, k;
7. for (k = 1; k <= n; k++)
8. for (i = 1; i <= n; i++)
9. for (j = 1; j <= n; j++)
10. p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
11. }
12. int max(int a, int b) {
13. ;
14. if (a > b)
15. return (a);
16. else
17. return (b);
18. }
19. void main() {
20. int p[10][10] = { 0 }, n, e, u, v, i, j;
21. printf("\n Enter the number of vertices:");
22. scanf("%d", &n);
23. printf("\n Enter the number of edges:");
24. scanf("%d", &e);
25. for (i = 1; i <= e; i++) {
26. //printf("\n Enter the end vertices of edge %d:", i);
27. scanf("%d%d", &u, &v);
28. p[u][v] = 1;
29. }
30. printf("\n Matrix of input data: \n");
31. for (i = 1; i <= n; i++) {
32. for (j = 1; j <= n; j++)
33. printf("%d\t", p[i][j]);
34. printf("\n");
35. }
36. warshal(p, n);
37. printf("\n Transitive closure: \n");
38. for (i = 1; i <= n; i++) {
39. for (j = 1; j <= n; j++)
40. printf("%d\t", p[i][j]);
41. printf("\n");
42. }
43. getch();
44. }
45. $ gcc WarshallTransitiveClosure.c
46. $ ./a.out
47.
48. Enter the number of vertices: 5
49. Enter the number of edges: 11
50. Enter the end vertices of edge 1: 1 1
51. Enter the end vertices of edge 2: 1 4
52. Enter the end vertices of edge 3: 3 2
53. Enter the end vertices of edge 4: 3 3
54. Enter the end vertices of edge 5: 3 4
55. Enter the end vertices of edge 6: 4 2
56. Enter the end vertices of edge 7: 4 4
57. Enter the end vertices of edge 8: 5 2
58. Enter the end vertices of edge 9: 5 3
59. Enter the end vertices of edge 10: 5 4
60. Enter the end vertices of edge 11: 5 5
61.
62. Matrix of input data:
63. 1 0 0 1 0
64. 0 0 0 0 0
65. 0 1 1 1 0
66. 0 1 0 1 0
67. 0 1 1 1 1
68.
69. Transitive closure:
70. 1 1 0 1 0
71. 0 0 0 0 0
72. 0 1 1 1 0
73. 0 1 0 1 0
74. 0 1 1 1 1
Out put
Following matrix shows the shortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0