Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- char **a;
- int *visited, n;
- void dfs(int x){
- int y;
- visited[x] = 1;
- printf(" %c ", 'A' + x); //index converted to char by adding A
- for(y = 0; y < n; y++)
- if(!visited[y] && a[x][y] == 'Y')
- dfs(y);
- }
- void buildAdjacentMatrix(){
- int i, j, choice;
- printf("\n Enter number of vertices:");
- scanf("%d",&n);
- a =(char**) malloc(sizeof(char*) * n);
- for(i = 0; i < n; i++) a[i] = (char*) malloc(n * sizeof(char)); //alternate to char a[n][n]
- visited = (int*) malloc(sizeof(int)*n); //alternate to int visited[n]
- for(i = 0; i < n; i++) visited[i] = 0;
- for(i = 0; i < n; i++)
- for(j = 0; j <= i; j++){
- printf("Are vertices %c and %c linked?: ", 'A' + i, 'A' + j);
- scanf("%d", &choice);
- if(choice == 1) a[i][j] = a[j][i] = 'Y';
- else a[i][j] = a[j][i] = 'N';
- }
- printf("The graph is:-\n");
- for(i = 0; i < n; i++) printf("\t%c", 'A'+i);
- printf("\n\n\n");
- for(i = 0; i < n; i++){
- printf("%c", 'A'+i);
- for(j = 0; j < n; j++) printf("\t%c", a[i][j]);
- printf("\n\n\n");
- }
- }
- int main(){
- char ch;
- buildAdjacentMatrix();
- printf("Start from which vertex?: ");
- fflush(stdin); //Clears input stream
- ch = getchar(); // char input from user
- if(ch >= 'A' && ch <= ('A' + n-1)) dfs(ch-'A'); //DFS starts from user inputted alphabet.
- else printf("Error.");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement