Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- int i, j, n, f = 0, r = 0, a[10][10], q[10], visited[10];
- void bfs(int u) {
- int v;//looping
- visited[u] = 1;
- q[r++] = u; // Enqueue at rear
- while(f < r) { // Use '<' instead of '<=' to avoid out-of-bounds
- u = q[f++]; // Dequeue from front
- for(v = 1; v <= n; v++) {
- if(a[u][v] == 1 && visited[v] == 0) {
- visited[v] = 1;
- q[++r] = v; // Enqueue at rear
- }
- }
- }
- }
- void main() {
- int source;
- printf("Enter the number of vertices\n");
- scanf("%d", &n);
- printf("Enter the adjacency matrix of the directed graph\n");
- for(i = 1; i <= n; i++)
- for(j = 1; j <= n; j++)
- scanf("%d", &a[i][j]);
- printf("Enter the source vertex\n");
- scanf("%d", &source);
- for(i = 1; i <= n; i++)
- visited[i] = 0;
- bfs(source);
- printf("From vertex %d the vertices\n", source);
- for(i = 1; i <= n; i++) {
- if(visited[i] == 1)
- printf("%d is reachable \n", i);
- }
- }
- #include<stdio.h>
- int n,a[10][10],visited[10];
- int dfs(int u){
- int v;
- visited[u]=1;
- for(v=1;v<=n;v++){
- if(a[u][v]==1 && visited[v]==0)
- dfs(v);
- }
- }
- void main(){
- int i,j,source;
- printf("enter the vertix");
- scanf("%d",&n);
- printf("enter the adjacency mat");
- for(i=1;i<=n;i++)
- for(j=1;j<=n;j++)
- scanf("%d",&a[i][j]);
- printf("the source vertic");
- scanf("%d",&source);
- for(i=1;i<=n;i++)
- visited[i]=0;
- dfs(source);
- for(i=1;i<=n;i++){
- if(visited[i]==0){
- printf("nope");
- }
- }
- printf("yes");
- }
Advertisement
Add Comment
Please, Sign In to add comment