Question

In: Computer Science

C Programming Question: Write a C - program to implement the following three operations: a) Breadth-first...

C Programming Question:

Write a C - program to implement the following three operations:

a) Breadth-first search using Adjacency List

b) Breadth-first search using Adjacency Matrix

c) Check whether a given graph is Bipartite using Breadth-first search (adjacency list).​​​​​​

Please take your time, but do submit the correct and full code. Thank you very much.

Solutions

Expert Solution

Hello, I am providing the correct answers to above question. If you have any doubt just ask in the comments section. In part (C) I don't got the required output in C language so I have done it in C++ language. Hope You Understand. Once Again if you have any doubt just ask it in comments section.

Ans a) -

#include <stdio.h>
#include <stdlib.h>

struct node {
        int val;
        struct node * next;
};

struct node * insert(struct node * head, int num)
{
        // This is exactly as Head Insertion of a Linked List.
        // We choose Head Insertion to get an O(1) Insertion
        // into an Adjacency List, Tail Insertion can also be used
        
        struct node * p = (struct node *) malloc(sizeof(struct node));
        
        p->val = num;
        p->next = head;

        return p;
}

void breadth_first_search(struct node * list[], int vertices, int parent[], int level[])
{
        struct node * temp;
        int i, par, lev, flag = 1;
        // 'lev' represents the level to be assigned
        // 'par' represents the parent to be assigned
        // 'flag' used to indicate if graph is exhausted
        
        lev = 0;
        level[1] = lev;
        // We start from node - 1
        // So, Node - 1 is at level 0
        // All immediate neighbours are at
        // level 1 and so on.
        
        while (flag) {
                flag = 0;
                for (i = 1; i <= vertices; ++i) {
                        if (level[i] == lev) {
                                flag = 1;
                                temp = list[i];
                                par = i;

                                while (temp != NULL) {
                                        if (level[temp->val] != -1) {
                                                temp = temp->next;
                                                continue;
                                        }
                                        
                                        level[temp->val] = lev + 1;
                                        parent[temp->val] = par;
                                        temp = temp->next;
                                }
                        }
                }
                
                ++lev;
        }
}

int main()
{
        int vertices, edges, i, j, v1, v2;
        
        printf("Enter the number of Vertices -\n");
        scanf("%d", &vertices);
        
        printf("Enter the number of Edges -\n");
        scanf("%d", &edges);

        struct node * adjacency_list[vertices + 1];
        // This is the table of our Adjacency List
        // Each element holds a Linked List
        // In C++ it can be made to hold a vector too
        // in that case, the declaration would be -
        // vector< vector<int> > adjacency_list;
        
        int parent[vertices + 1];
        // Each element of Parent Array holds the Node value of its parent
        int level[vertices + 1];        
        // Each element of Level Array holds the Level value of that node
        
        for (i = 0; i <= vertices; ++i) {
                //Initialising our arrays
                adjacency_list[i] = NULL;
                parent[i] = 0;
                level[i] = -1;
        }

        for (i = 1; i <= edges; ++i) {
                scanf("%d%d", &v1, &v2);
                adjacency_list[v1] = insert(adjacency_list[v1], v2);
                adjacency_list[v2] = insert(adjacency_list[v2], v1);
                // For edge {v1, v2} = {2, 3},
                // Adjacency List holds 2----3
                // and 3-----2 as edges
        }
        
        // Printing Adjacency List
        printf("\nAdjacency List -\n");
        for (i = 1; i <= vertices; ++i) {
                printf("%d -> ", i);
                
                struct node * temp = adjacency_list[i];
                
                while (temp != NULL) {
                        printf("%d -> ", temp->val);
                        temp = temp->next;
                }
                
                printf("NULL\n");
        }

        breadth_first_search(adjacency_list, vertices, parent, level);
        
        // Level Array
        printf("\nLevel and Parent Arrays -\n");
        for (i = 1; i <= vertices; ++i) {
                printf("Level of Node %d is %d, Parent is %d\n", i, level[i], parent[i]);
        }
        
        return 0;
}
 

Ans b) -

#include<stdio.h>
#include<stdlib.h>

#define MAX 100

int n;
int adj[MAX][MAX]; //adjacency matrix, where adj[i][j] = 1, denotes there is an edge from i to j
int visited[MAX]; //visited[i] can be 0 / 1, 0 : it has not yet printed, 1 : it has been printed
void create_graph();
void BF_Traversal();
void BFS();

int queue[MAX], front = -1,rear = -1;
void push_queue(int vertex);
int pop_queue();
int isEmpty_queue();

int main()
{
create_graph();
BFS();
return 0;
}


void BFS()
{
int v;

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

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


int i;

push_queue(v);

while(!isEmpty_queue())
{

v = pop_queue( );
if(visited[v]) //if it has already been visited by some other neighbouring vertex, it should not be printed again.
continue;

printf("%d ",v);
visited[v] = 1;
  
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && visited[i] == 0)
{
push_queue(i);
}
}
}
printf("\n");
}

void push_queue(int vertex)
{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}

int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}

int pop_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}

delete_item = queue[front];
front = front+1;
return delete_item;
}

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");
scanf("%d",&n);
max_edge = n*(n-1); //assuming each vertex has an edge with remaining (n-1) vertices

for(count=1; count<=max_edge; count++)
{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))
break;

if(origin>=n || destin>=n || origin<0 || destin<0)
{
printf("Invalid edge!\n");
count--;
}
else
{
adj[origin][destin] = 1;
adj[destin][origin] = 1; // assuming it is a bi-directional graph, we are pushing the reverse edges too.
}
}
}

Ans C -

#include<bits/stdc++.h>
 
using namespace std;
 
int n,e,i,j;
vector<vector<int> > graph;
vector<int> color;
bool vis[100011];
 
bool isBipartite()
{
    color[0] = 1; // Mark colour as 1 for first vertex.
    queue <int> q;
    q.push(0);
    while (!q.empty())
    {
        int temp = q.front();
        q.pop();
        for (i=0;i<n;i++)
        {
            if (graph[temp][i] && color[i] == -1) //if there is an edge, and colour is not assigned
            {
                color[i] = 1 - color[temp];
                q.push(i);
            }
            else if (graph[temp][i] && color[i] == color[temp]) // if there is an edge and both vertices have same colours
                return 0;                                   // graph is not bipartite
        }
    }
    return 1;
}
 
int main()
{
    int x,y;
    cout<<"Enter number of vertices and edges respectively:";
    cin>>n>>e;
    cout<<"\n";
    graph.resize(n);
    color.resize(n,-1);
    memset(vis,0,sizeof(vis));
    for(i=0;i<n;i++)
        graph[i].resize(n);
    for(i=0;i<e;i++)
    {
        cout<<"\nEnter edge vertices of edge "<<i+1<<" :";
        cin>>x>>y;
        x--; y--;
        graph[x][y]=1;
        graph[y][x]=1;
    }
    if(isBipartite())
        cout<<"Yes, The given graph is Bipartite.\n";
    else
        cout<<"No, The given graph is not Bipartite.\n";
    return 0;
}

Related Solutions

Use C programming to Implement the breadth-first tree traversal. The tasks are: a) Build the tree....
Use C programming to Implement the breadth-first tree traversal. The tasks are: a) Build the tree. b) Perform breadth first traversal on the tree that you have built at step a). Note: "Please comment the program"
C Programming Question: Q) Write a C - program to implement an Uprooted version (Save to...
C Programming Question: Q) Write a C - program to implement an Uprooted version (Save to parent pointer instead of child pointer, ie. parent of top is null) of Kruskal's Minimum Spanning Tree with adjacency list and min-heap as the additional data structure. Note: Please implement it in C and also keep the above conditions in mind. You can take your time. Thank you.
In this assignment, you will implement Breadth First Search (BFS). The input to your program is...
In this assignment, you will implement Breadth First Search (BFS). The input to your program is a graph in the adjacency list format. The input graph has at most 100 vertices. Your program must initiate a BFS from vertex 2 of the graph. If the graph is connected, your program must output “Graph is connected”. If the graph is disconnected, your program must output “Graph is not connected”. Your program should read from an input file: data2.txt and write to...
Write a C program to implement the priority queue with the operations insert and extractmax. Sample...
Write a C program to implement the priority queue with the operations insert and extractmax. Sample : ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 2 enter any key to go to main menu ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 4 enter any key to go to main menu ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 6 enter any key to go to main menu...
C Programming Question: Q) Write a C - program to check whether a given graph is...
C Programming Question: Q) Write a C - program to check whether a given graph is Bipartite using Breadth-first search (adjacency list) Do take your time but please do post full code and also please do it in C.
write pseudocode not c program If- else programming exercises 1.    Write a C program to find...
write pseudocode not c program If- else programming exercises 1.    Write a C program to find maximum between two numbers. 2.    Write a C program to find maximum between three numbers. 3.    Write a C program to check whether a number is negative, positive or zero. 4.    Write a C program to check whether a number is divisible by 5 and 11 or not. 5.    Write a C program to check whether a number is even or odd. 6.    Write...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement:...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement: The program will read from standard input two things - a string str1 on the first line of stdin (this string may be an empty string) - a string str2 on the second line of stdin (this string may be an empty string) Note that stdin does not end with '\n'. The program will output a string that is the concatenation of string str1...
Write a program in C or C++ that spawns three child processes. The first child sends...
Write a program in C or C++ that spawns three child processes. The first child sends a signal to the parent (you'll need the parent's pid!), which the parent shall catch. The second child waits for 10 seconds and then terminates. Once the parent detects that both of these has happened, it should signal the third child to terminate.
Write and test a C program to implement Bubble Sort. . In your C program, you...
Write and test a C program to implement Bubble Sort. . In your C program, you should do: Implement the array use an integer pointer, get the size of the array from standard input and use the malloc function to allocate the required memory for it. Read the array elements from standard input. Print out the sorted array, and don’t forget to free the memory. Debug your program using Eclipse C/C++ CDT.
Using C# programming language, Write a program that sort three numbers entered by the user using...
Using C# programming language, Write a program that sort three numbers entered by the user using only if and nested if statements. If for instance the user entered 5, 2, and 7; the program should display 2,5,7.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT