Vikhyath_11

p2

Jul 26th, 2024
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. int i, j, n, f = 0, r = 0, a[10][10], q[10], visited[10];
  4.  
  5. void bfs(int u) {
  6. int v;//looping
  7. visited[u] = 1;
  8. q[r++] = u; // Enqueue at rear
  9. while(f < r) { // Use '<' instead of '<=' to avoid out-of-bounds
  10. u = q[f++]; // Dequeue from front
  11. for(v = 1; v <= n; v++) {
  12. if(a[u][v] == 1 && visited[v] == 0) {
  13. visited[v] = 1;
  14. q[++r] = v; // Enqueue at rear
  15. }
  16. }
  17. }
  18. }
  19.  
  20. void main() {
  21. int source;
  22. printf("Enter the number of vertices\n");
  23. scanf("%d", &n);
  24. printf("Enter the adjacency matrix of the directed graph\n");
  25. for(i = 1; i <= n; i++)
  26. for(j = 1; j <= n; j++)
  27. scanf("%d", &a[i][j]);
  28. printf("Enter the source vertex\n");
  29. scanf("%d", &source);
  30. for(i = 1; i <= n; i++)
  31. visited[i] = 0;
  32. bfs(source);
  33. printf("From vertex %d the vertices\n", source);
  34. for(i = 1; i <= n; i++) {
  35. if(visited[i] == 1)
  36. printf("%d is reachable \n", i);
  37. }
  38. }
  39.  
  40.  
  41.  
  42.  
  43.  
  44. #include<stdio.h>
  45. int n,a[10][10],visited[10];
  46. int dfs(int u){
  47. int v;
  48. visited[u]=1;
  49. for(v=1;v<=n;v++){
  50. if(a[u][v]==1 && visited[v]==0)
  51. dfs(v);
  52. }
  53. }
  54. void main(){
  55. int i,j,source;
  56. printf("enter the vertix");
  57. scanf("%d",&n);
  58. printf("enter the adjacency mat");
  59. for(i=1;i<=n;i++)
  60. for(j=1;j<=n;j++)
  61. scanf("%d",&a[i][j]);
  62. printf("the source vertic");
  63. scanf("%d",&source);
  64. for(i=1;i<=n;i++)
  65. visited[i]=0;
  66. dfs(source);
  67. for(i=1;i<=n;i++){
  68. if(visited[i]==0){
  69. printf("nope");
  70. }
  71. }
  72. printf("yes");
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment