dijkstra algorithm online code example

Example 1: dijkstra algorithm c++

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int n = 9;
	
	int mat[9][9] = { { 100,4,100,100,100,100,100,8,100}, 
                      { 4,100,8,100,100,100,100,11,100}, 
                      {100,8,100,7,100,4,100,100,2}, 
                      {100,100,7,100,9,14,100,100,100}, 
                      {100,100,100,9,100,100,100,100,100}, 
                      {100,100,4,14,10,100,2,100,100}, 
                      {100,100,100,100,100,2,100,1,6}, 
                      {8,11,100,100,100,100,1,100,7}, 
                      {100,100,2,100,100,100,6,7,100}};
	
	int src = 0;
	int count = 1;
	
	int path[n];
	for(int i=0;i<n;i++)
		path[i] = mat[src][i];
	
	int visited[n] = {0};
	visited[src] = 1;
	
	while(count<n)
	{
		int minNode;
		int minVal = 100;
		
		for(int i=0;i<n;i++)
			if(visited[i] == 0 && path[i]<minVal)
			{
				minVal = path[i];
				minNode = i;
			}
		
		visited[minNode] = 1;
		
		for(int i=0;i<n;i++)
			if(visited[i] == 0)
				path[i] = min(path[i],minVal+mat[minNode][i]);
					
		count++;
	}
	
	path[src] = 0;
	for(int i=0;i<n;i++)
		cout<<src<<" -> "<<path[i]<<endl;
	
	return(0);
}

Example 2: Dijkstra’s Algorithm code in C

#include<stdio.h>#include<conio.h>#define INFINITY 9999#define MAX 10 void dijikstra(int G[MAX][MAX], int n, int startnode); void main(){	int G[MAX][MAX], i, j, n, u;	clrscr();	printf("\nEnter the no. of vertices:: ");	scanf("%d", &n);	printf("\nEnter the adjacency matrix::\n");	for(i=0;i < n;i++)		for(j=0;j < n;j++)			scanf("%d", &G[i][j]);	printf("\nEnter the starting node:: ");	scanf("%d", &u);	dijikstra(G,n,u);	getch();} void dijikstra(int G[MAX][MAX], int n, int startnode){	int cost[MAX][MAX], distance[MAX], pred[MAX];	int visited[MAX], count, mindistance, nextnode, i,j;	for(i=0;i < n;i++)		for(j=0;j < n;j++)			if(G[i][j]==0)				cost[i][j]=INFINITY;			else				cost[i][j]=G[i][j];		for(i=0;i< n;i++)	{		distance[i]=cost[startnode][i];		pred[i]=startnode;		visited[i]=0;	}	distance[startnode]=0;	visited[startnode]=1;	count=1;	while(count < n-1){		mindistance=INFINITY;		for(i=0;i < n;i++)			if(distance[i] < mindistance&&!visited[i])			{				mindistance=distance[i];				nextnode=i;			}		visited[nextnode]=1;		for(i=0;i < n;i++)			if(!visited[i])				if(mindistance+cost[nextnode][i] < distance[i])				{					distance[i]=mindistance+cost[nextnode][i];					pred[i]=nextnode;				}			count++;	} 	for(i=0;i < n;i++)		if(i!=startnode)		{			printf("\nDistance of %d = %d", i, distance[i]);			printf("\nPath = %d", i);			j=i;			do			{				j=pred[j];				printf(" <-%d", j);			}			while(j!=startnode);		}}

Tags:

Cpp Example