#include <stdio.h>
#include
<stdlib.h>
struct
Node
{
int data;
struct Node* next;
};
typedef
struct Node Node;
void
addEdge(Node** adjList, int src, int dest)
{
Node* newNode =
(Node*)malloc(sizeof(Node));
newNode->data = dest;
newNode->next = adjList[src];
adjList[src] = newNode;
}
void
printAdjacencyList(Node** adjList, int numVertices)
{
for (int i = 0; i < numVertices; i++)
{
printf("Vertex %d -> ", i);
Node* current = adjList[i];
while (current)
{
printf("%d ",
current->data);
current = current->next;
}
printf("\n");
}
}
int
main()
{
int numVertices;
printf("Enter the number of vertices
in the graph: ");
scanf("%d", &numVertices);
int
adjacencyMatrix[numVertices][numVertices];
printf("Enter the adjacency
matrix:\n");
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices;
j++) {
scanf("%d",
&adjacencyMatrix[i][j]);
}
}
Node* adjacencyList[numVertices];
for (int i = 0; i < numVertices; i++)
{
adjacencyList[i] = NULL;
}
for (int i = 0; i < numVertices; i++)
{
for (int j = 0; j < numVertices;
j++)
{
if (adjacencyMatrix[i][j] == 1)
{
addEdge(adjacencyList, i, j);
}
}
}
printf("Adjacency List:\n");
printAdjacencyList(adjacencyList,
numVertices);
return 0;
}
No comments:
Post a Comment