| #include <stdio.h> | |
| #define MAX 100 | |
| int n, a[20][20], visited[20]; | |
| char name[20]; | |
| int Q[MAX], f = -1, r = -1; | |
| void enqueue(int num) { | |
| if(r == MAX -1) { | |
| printf("Queue Overflow\n"); | |
| } else { | |
| r++; | |
| Q[r] = num; | |
| if(f == -1) { | |
| f = 0; | |
| } | |
| } | |
| } | |
| int dequeue() { | |
| int num; | |
| if(isEmpty()) { | |
| return -1; | |
| } else { | |
| num = Q[f]; | |
| f++; | |
| return num; | |
| } | |
| } | |
| int isEmpty() { | |
| if(f == -1 || f > r) { | |
| return 1; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| void BFS(int v) { | |
| int i; | |
| visited[v] = 1; | |
| enqueue(v); | |
| while(!isEmpty()) { | |
| v = dequeue(); | |
| printf("%c -> ", name[v]); | |
| for(i = 0; i < n; i++) { | |
| if(a[v][i] == 1 && visited[i] == 0) { | |
| enqueue(i); | |
| visited[i] = 1; | |
| } | |
| } | |
| } | |
| } | |
| int main() { | |
| int i, j; | |
| printf("Depth First Search 1.0:\n"); | |
| printf("Enter number of vertices: "); | |
| scanf("%d", &n); | |
| printf("Enter name of vertices: "); | |
| for(i = 0; i < n; i++) { | |
| // Note the space here | |
| scanf(" %c", &name[i]); | |
| } | |
| for(i = 0; i < n; i++) { | |
| visited[i] = 0; | |
| } | |
| printf("Enter adjacency matrix: \n"); | |
| for(i = 0; i < n; i++) { | |
| for(j = 0; j < n; j++) { | |
| scanf("%d", &a[i][j]); | |
| } | |
| } | |
| for(i = 0; i < n; i++) { | |
| if(visited[i] == 0) { | |
| BFS(i); | |
| } | |
| } | |
| } |
Friday, 4 November 2016
Program 19 - BFS
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment