Give a ahortest path from a source in an unweighted graph using an adjacency matrix.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<stdlib.h>
#define N 20
typedef struct {
	int V;
	int E;
	int **Adj; // since we need 2 dimensional matrix
} Graph;

typedef int element;

typedef struct 
{
	element data[N]; /* queue content */
	int front, length;
} queue;


queue CreateQueue()
{
	queue q;
	q.front = 0; q.length=0;
	return q;
}
int isEmptyQueue(queue q)
{
	return q.length == 0;
}

int isFullQueue(queue q)
{
	return q.length ==N;
}

int EnQueue(queue *q, element e)
{
	if (isFullQueue(*q)) return 0;
	q->data[(q->front + q->length)%N] = e;
	q->length = q->length + 1;
	return 1;
}

int DeQueue(queue *q)
{
	if (isEmptyQueue(*q)) return 0;
	q->front=(q->front + 1) % N;
	q->length--;
	return 1;
}

int Front(queue q, element *e)
{
	if (isEmptyQueue(q)) return 0;
	*e = q.data[q.front];
	return 1;
}

Graph* adjacencyMatrix() {
	int i, u, v;
	Graph* G = (Graph*)malloc(sizeof(Graph));
	printf("Enter the number of Vertices: ");
	scanf("%d", &G->V);
	printf("Enter the number of Edges: ");
	scanf("%d", &G->E);
	G->Adj = (int **)malloc(G->V * sizeof(int*));
	for (u = 0; u < G->V; u++)
		G->Adj[u] = (int *)malloc(G->V * sizeof(int));

	for (u = 0; u<G->V; u++)
		for (v = 0; v<G->V; v++)
			G->Adj[u][v] = 0;
	for (i = 0; i < G->E; i++) {
		printf("Enter the edge: ");
		scanf("%d %d", &u, &v);
		// for undirected graph, set both
		G->Adj[u][v] = 1;
		// G->Adj[v][u] = 1;
	}
	return G;
}


void UnweightedShortestPath(Graph *G, int s) {
	queue q;
	int v, w;
	int *distance, *Path;

	Path = (int *)malloc(G->V * sizeof(int));
	distance = (int *)malloc(G->V * sizeof(int));
	for (v = 0; v < G->V; v++)
		distance[v] = -1;

	q = CreateQueue();
	EnQueue(&q, s);
	distance[s] = 0;
	while (Front(q, &v)) {
		DeQueue(&q);
		for (w = 0; w < G->V; w++)
			if (G->Adj[v][w] == 1)
				if (distance[w] == -1) // each vertex examined at most once
				{
					distance[w] = distance[v] + 1;
					Path[w] = v;
					EnQueue(&q, w); // each vertex enqueued at most once
				}
	}
	for (v = 0; v < G->V; v++)
		printf("%d to %d weight %d\n", Path[v], v,distance[v] );
}

 

void test() {
	Graph *G = adjacencyMatrix();
	UnweightedShortestPath(G, 2);
}


int main()
{
	test();
	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Star pattern 22