Find All Remaining Vertices In Graph After Marking Shortest Path For Neighbours


Algorithms concerning graph search algorithms traverse a graph in pursuit of broad discovery or targeted search. These algorithms cut pathways across the network, but no one expects those paths to be computationally optimum. Pathfinding algorithms are assembled on graph search techniques as well as these investigate pathways amongst vertices, beginning at a specific node and going via connections till the goal is visited.

What Are Graphs?

Graphs are data structures that reflect "connections" among sets of components.

These items are known as nodes. Edges are the connections between nodes.

Shortest Path

The Shortest Path algorithms locate the shortest paths or the edge(s) with the least weight between any two nodes or vertices. Because it operates in real-time, it is excellent for user interaction and dynamic workflows.

Algorithm Type

Function 

Example Use

Shortest Route Variations 

Finds the shortest pathway across two vertices.

Obtaining driving directions across different points

"Single Source Shortest Path"

Locates the shortest route between the root node and all other nodes.

Cheapest possible call route

"All Pairs Shortest Path"

Finds the shortest path across any two nodes in a graph.

Considering other pathways to avoid traffic congestion.

The Dijkstra Algorithm

Dijkstra's Algorithm constructs a group of nodes with the least distance from the source to obtain the "shortest path tree" from just one source node.

What are the fundamentals of the Dijkstra Algorithm?

The basics of the Dijkstra Algorithm are listed below −

  • Dijkstra's Algorithm starts at the node you specify (also known as the starting node), then proceeds to analyze the graph for discovering the shortest pathway connecting that vertex and all other nodes within the graph.

  • This technique maintains track of the shortest distance between the source node and each node and changes the values when it identifies or detects a shorter route.

  • Once locating the minimum distance connecting the source and the other node is accomplished, that vertex is marked as "visited" and is added to the path.

  • The technique is repeated until all of the vertices in the graph are included in the path.  Hence, one establishes the pathway that links the primary node to every node through the shortest feasible path to each node.

Note

Graph analytics will utilize terminologies when characterising linkages and pathways like −

  • "Weight" − the numeric entity of a relationship's specific characteristic.

  • "Cost" – we will encounter it frequently while assessing a path's overall weight.

  • "Distance" is a common moniker for the connecting attribute that reflects the distance travelled across two nodes within an algorithm.

  • "Hop" refers to the number of connections across two vertices. 

Main Uses Of Dijkstra's Algorithm

This method determines the shortest route connecting the present position and the intended location in GPS devices. It has several uses in industry, mainly in areas that require modelling of networks.

Can Dijkstra's Algorithm Work If The Graph's Edges Have Negative Weight?

The answer is NO.

Dijkstra's Algorithm can function only with graphs having positive weights. This is due to the fact that the edges' weights must be added in order to detect the shortest route.

The algorithm isn't going to work successfully for a graph having a negative weight. When a node is tagged "visited," the present pathway that leads to the node becomes the shortest one. Negative weights can alter this because the total weight will be diminished post this phase.

What to Do Upon Completing Marking The Shortest Path For Neighbours In The Graph To Identify All Remaining Vertices?

The procedure is touring every vertex and labelling the node with the lowest column number links to the principal vertex through the least weighted edge.ng the vertex linked to the present node via the least weighted edge, then discover each unmarked edge.

To Overcome This Issue, Follow These Steps

Iterate over an entire adjacency matrix utilizing two loops, j and i.

Identify the least result in the matrix of adjacencies for every (row); the node with the lowest column number links to the principal vertex through the least weighted edge.

Using a Boolean array, mark this vertex for each vertex.

Print every vertex or node that is not marked in the Boolean array.

This method is implemented as follows

Example

#include <iostream>
#include <string>
#include <vector>
#include <limits>
 
// Stdc++11 code to implement the approach
class GFG{
   
   // Function to calculate the number of unmarked edges
   public:
   static std::vector<bool> markedNodesCounter(std::vector<std::vector<int>> &A, int V){
       
      // Initialising visited array
      std::vector<bool> marked(V);
       
      // Loop to iterate through every node
      for (int i = 0; i < V; i++){
           
         // Initialising the minimum distance and the node closest to the current node
         int minweight = std::numeric_limits<int>::max();
         int min = V + 1;
           
         // loop to find the weights from current node to every other node
         for (int j = 0; j < V; j++){
            if (i == j){
               continue;
            }
            if (A[i][j] < minweight){
               minweight = A[i][j];
               min = j;
            }
         }
         // Marking the closest node
         marked[min] = true;
      }
      // Returning the answer
      return marked;
   }
   // Driver Code
   static void main(std::vector<std::string> &args){
      int V = 3;
      std::vector<std::vector<int>> A{{0, 10, 50}, {10, 0, 30}, {50, 30, 0}};
      // Getting the result
      std::vector<bool> marked = GFG::markedNodesCounter(A, V);
      // Printing the result
      bool flag = false;
      for (int i = 0; i < V; i++){
         if (!marked[i]){
            std::cout << std::to_string(i) + " ";
            flag = true;
         }
      }
      if (!flag){
         std::cout << "-1" << std::endl;
      }else{
         std::cout << std::endl;
      }
   }
};
int main(int argc, char **argv){
   std::vector<std::string> parameter(argv + 1, argv + argc);
   GFG::main(parameter);
   return 0;
};

Output

According to the above code −

2

Auxiliary Space is O(V) and time complexity is O(V2) for generating one additional array of size V and initializing two nested loops ranging from 0 to V respectively.

What Situations Call For the Shortest Path?

Using the Shortest Path algorithm, you may determine the best paths between two nodes depending on the hop count or any other weighted connection value. It may offer instantaneous responses concerning degrees of separation, the minimum route across two locations, or the cheapest way. One may also utilize this approach for investigating the relationships between specific nodes.

Conclusion

Pathfinding algorithms can help us comprehend the relationships between our data. Dijkstra's Algorithm discovers the shortest route across two nodes of a network. This approach employs the edge weights to detect the path that reduces the entire weight connecting the primary vertex to all vertices.

Updated on: 09-Oct-2023

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements