Search
 
SCRIPT & CODE EXAMPLE
 

CPP

C++ code for Dijkstra’s Algorithm

#include<iostream>
#include<climits>
using namespace std;

int miniDist(int distance[], bool Tset[]) // finding minimum distance
{
    int minimum=INT_MAX,ind;
              
    for(int k=0;k<6;k++) 
    {
        if(Tset[k]==false && distance[k]<=minimum)      
        {
            minimum=distance[k];
            ind=k;
        }
    }
    return ind;
}

void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix 
{
    int distance[6]; // // array to calculate the minimum distance for each node                             
    bool Tset[6];// boolean array to mark visited and unvisited for each node
    
     
    for(int k = 0; k<6; k++)
    {
        distance[k] = INT_MAX;
        Tset[k] = false;    
    }
    
    distance[src] = 0;   // Source vertex distance is set 0               
    
    for(int k = 0; k<6; k++)                           
    {
        int m=miniDist(distance,Tset); 
        Tset[m]=true;
        for(int k = 0; k<6; k++)                  
        {
            // updating the distance of neighbouring vertex
            if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX && distance[m]+graph[m][k]<distance[k])
                distance[k]=distance[m]+graph[m][k];
        }
    }
    cout<<"Vertex		Distance from source vertex"<<endl;
    for(int k = 0; k<6; k++)                      
    { 
        char str=65+k; 
        cout<<str<<"			"<<distance[k]<<endl;
    }
}

int main()
{
    int graph[6][6]={
        {0, 1, 2, 0, 0, 0},
        {1, 0, 0, 5, 1, 0},
        {2, 0, 0, 2, 3, 0},
        {0, 5, 2, 0, 2, 2},
        {0, 1, 3, 2, 0, 1},
        {0, 0, 0, 2, 1, 0}};
    DijkstraAlgo(graph,0);
    return 0;                           
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: error handling in c++ 
Cpp :: automatic legend matlab 
Cpp :: descending order c++ 
Cpp :: c++ hash combine 
Cpp :: how to slice vector in c++ 
Cpp :: position of max element in vector c++ 
Cpp :: C++ New Lines 
Cpp :: C++ Infinite while loop 
Cpp :: How do I read computer current time in c++ 
Cpp :: travelling salesman problem c++ 
Cpp :: c++ program to generate all the prime numbers between 1 and n 
Cpp :: c++ exceptions 
Cpp :: Function to calculate compound interest in C++ 
Cpp :: c++ region 
Cpp :: c++ set swap 
Cpp :: c++ template 
Cpp :: break statement in c++ program 
Cpp :: opencv c++ feature detection 
Cpp :: stack class implementation to file unix-style in c++ 
Cpp :: ue4 c++ replicate actor variable 
Cpp :: how to access a vector member by its index 
Cpp :: program to swap max and min in matrix 
Cpp :: c++ polymorphism 
Cpp :: . Write a C++ program to calculate area of a Triangle 
Cpp :: lists occurrences of characters in the string c++ 
Cpp :: c++ catch Unhandled exception 
Cpp :: size of unordered_set 
Cpp :: round c++ 
Cpp :: and c++ 
Cpp :: enum in c++ 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =