Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.8 kB
2
Indexable
Never
#include<stdio.h>
#include<stdlib.h>

int graph[100][100];
int visited[100];

int selectOption();

int enqueue(int data[], int re, int v, int n);
int dequeue(int data[], int fr, int n);
void BFS(int data[], int re, int fr, int n);
int isEmpty(int re, int fr);

int top = -1;

int main()
{
    //printf("hello\n");
    //int data[100], n, ch, v;//data = stack
    int queue[100], n, ch, fr = 0, re = 0, qSize = 0, v;
    int i, j;
    int vertex, source;

    char s;


    ch = selectOption();

    while(ch != 0)
    {
        if(ch == 1)
        {
            printf("enter number of vertex: ");
            scanf("%d",&n);

            for(i = 0; i < n; i++)
            {
                for(j = i+1; j < n; j++)
                {
                    printf("edge between %c and %c: ", i+65, j+65);
                    scanf("%d",&graph[i][j]);
                    graph[j][i] = graph[i][j];
                }
            }
        }
        else if(ch == 2)
        {

        }
        else if(ch == 3)
        {
            BFS(queue, re, fr, n);
        }
        else if(ch == 4)
        {
            printf("adjacency matrix\n");
            for(i = 0; i < n; i++)
            {
                for(j = 0; j < n; j++)
                {
                    printf("%d\t", graph[i][j]);
                }
                printf("\n");
            }
        }
        else
        {
            printf("Invalid choice. Please try again.\n\n\n");
        }
        ch = selectOption();
    }
    return 0;
}

int selectOption()
{
    int ch;
    printf("1. create graph\n");
    printf("2. dfs\n");
    printf("3. bfs\n");
    printf("4. print adjacency matrix\n");
    printf("0. Exit\n");
    printf("Enter your choice: ");
    scanf("%d",&ch);
    return ch;
}



void BFS(int data[], int re, int fr, int n)
{
    int v;

   for(v=0; v<n; v++)
      visited[v] = 0;

   printf("Enter Start Vertex for BFS: \n");
   scanf("%d", &v);


   int i;

   enqueue(data, re, v, n);

   while(!isEmpty(re, fr))
   {

      v = dequeue(data, fr, n);
       if(visited[v])
           continue;

      printf("%d ",v);
      visited[v] = 1;

      for(i=0; i<n; i++)
      {
         if(graph[v][i] == 1 && visited[i] == 0)
         {
            enqueue(data, re, i, n);
         }
      }
   }
   printf("\n");
}

int enqueue(int data[], int re, int v, int n)
{
    data[re] = v;
    re++;
    if(re == n)
        re = 0;
    return re;

}

int dequeue(int data[], int fr, int n)
{
    fr = (fr+1)%n;
    return fr;
}

int isEmpty(int re, int fr)
{
   if(fr == -1 || fr > re)
      return 1;
   else
      return 0;
}