Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #define MAX 20
- int graph_type,n,max_edges,i,j,origin,destination;
- int adj[MAX][MAX];
- void create_graph();
- void display();
- void insert_edge(int, int);
- void delete_edge(int, int);
- int main()
- { int choice;
- create_graph();
- while(1)
- { printf("1.Insert an edge: \n");
- printf("2.Delete an edge: \n");
- printf("3.Display: \n");
- printf("4.Exit: \n");
- printf("Enter your choice: ");
- scanf("%d", & choice);
- switch(choice)
- { case 1: printf("Enter an edge to be inserted: ");
- scanf("%d %d",&origin,&destination);
- insert_edge(origin,destination);
- break;
- case 2: printf("Enter an edge to be deleted: ");
- scanf("%d %d",&origin,&destination);
- delete_edge(origin,destination);
- break;
- case 3: display();
- break;
- case 4: exit(1);
- default:printf("Wrong choice \n");
- break;
- }//switch
- }//while
- return 0;
- }//main
- void create_graph()
- {
- printf("Enter Graph type '1' for undirected and '2' for directed graph: ");
- scanf("%d",&graph_type);
- printf("Enter number of vertices: ");
- scanf("%d",&n);
- if (graph_type == 1)
- max_edges = n*(n-1)/2;
- else
- max_edges = n*(n-1);
- for(i=0;i<=max_edges;i++)
- { printf("Enter edges (origin & destination), Enter -1 -1 to exit: ");
- //enter value as 'int' space 'int' because here is '%d' space '%d'
- scanf("%d %d",&origin,&destination);
- if(origin == -1 && destination == -1)
- break;
- if(origin>=n || destination >= n || origin < 0 || destination < 0)//checking for limitations
- { printf("Invalid data please enter again: \n");
- i--;
- }
- else
- adj[origin][destination] = 1;
- if(graph_type == 1) // since for undirected graph origin & destination are exchangable
- adj[destination][origin] =1;
- }
- }//end of create_graph
- void display()
- { printf("\nThe adjacent matrix is following: \n\n");
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- printf("%4d",adj[i][j]);
- printf("\n");
- }
- }//end of display
- void insert_edge(int origin, int destination)
- { if(origin < 0 || origin >= n)
- { printf("Origin does not exist: \n");
- return;
- }
- if(destination < 0 || destination >= n)
- { printf("Destination does not exist: \n");
- return;
- }
- adj[origin][destination] = 1;
- if (graph_type == 1)
- adj[destination][origin] =1;
- }//end of insert_edge
- void delete_edge(int origin, int destination)
- { if(origin < 0 || origin >= n || destination < 0 || destination >= n || adj[origin][destination]==0)
- { printf("This edge does not exist: \n");
- return;
- }
- adj[origin][destination] = 0;
- if (graph_type == 1)
- adj[destination][origin] =0;
- }//end of delete_edge
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement