Experiment Name_graph
Experiment Name_graph
// BFS algorithm
void bfs(struct GraphList* graph, int startVertex) {
struct Node* adjList;
struct Node* temp;
visited[startVertex] = 1;
queue[rear] = startVertex;
rear++;
temp = graph->adjLists[currentVertex];
while (temp) {
int adjVertex = temp->vertex;
if (visited[adjVertex] == 0) {
queue[rear] = adjVertex;
rear++;
visited[adjVertex] = 1;
}
temp = temp->next;
}
}
free(visited);
free(queue);
}
// DFS algorithm
void dfs(struct GraphList* graph, int vertex) {
struct Node* adjList = graph->adjLists[vertex];
struct Node* temp = adjList;
graph->visited[vertex] = 1;
printf("Visited %d\n", vertex);
if (graph->visited[connectedVertex] == 0) {
dfs(graph, connectedVertex);
}
temp = temp->next;
}
}
// Main function
int main() {
int vertices, choice, src, dest, startVertex;
while (1) {
printf("\nGraph Operations:\n");
printf("1. Add Edge\n");
printf("2. Print Graph (Adjacency List)\n");
printf("3. Print Graph (Adjacency Matrix)\n");
printf("4. BFS\n");
printf("5. DFS\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the source and destination vertices: ");
scanf("%d %d", &src, &dest);
addEdgeList(graphList, src, dest);
addEdgeMatrix(graphMatrix, src, dest);
break;
case 2:
printf("Graph (Adjacency List):\n");
printGraphList(graphList);
break;
case 3:
printf("Graph (Adjacency Matrix):\n");
printGraphMatrix(graphMatrix);
break;
case 4:
printf("Enter the start vertex for BFS: ");
scanf("%d", &startVertex);
bfs(graphList, startVertex);
break;
case 5:
printf("Enter the start vertex for DFS: ");
scanf("%d", &startVertex);
for (int i = 0; i < vertices; i++) // Reset visited array for DFS
graphList->visited[i] = 0;
dfs(graphList, startVertex);
break;
case 6:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Output: