How to Implement the shortest path algorithm in JAVA: dijela Algorithm

The shortest path is a classic algorithm in graph theory. It is designed to find the shortest path between two nodes in the graph, the most common algorithms are Dijkstra algorithm, SPFA algorithm \ Bellman-Ford algorithm, Floyd algorithm \ Floyd-Warshall algorithm, and Johnson algorithm. This blog will focus on Dijkstra algorithm.

**Dijela Algorithm**

The dijela algorithm was proposed by Dutch computer scientist dikela in 1959. Therefore, it is also called the dikela algorithm. It is the shortest path algorithm from one vertex to the other vertices. It solves the shortest path problem in the directed graph. The main feature of the dijela algorithm is to expand horizontally from the starting point until the end point is reached. You can view the specific calculation rules.

Through this figure, we can simply understand the basic idea of the dijela algorithm. Below we will implement this algorithm through JAVA.

**Algorithm Implementation**

Before implementation, we have a basic convention that we use a positive integer to encode each node on the way. The distance between two adjacent points is a positive integer, in the figure, the distance between two directly adjacent points is saved to the map, that is, to find the shortest distance, we need to implement this method:

public MinStep getMinStep(int start, int end, final HashMap
> stepLength);

The first parameter is the number of the Start Node, the second parameter is the number of the end node, and the third parameter is a map composed of directly adjacent two nodes in the figure. The third parameter will be described in detail later. Here we define an interface to calculate the shortest path between two points, as follows:

/** [Email protected]: */package com. lulei. distance; import java. util. hashMap; import com. lulei. distance. bean. minStep; public interface Distance {public static final MinStep UNREACHABLE = new MinStep (false,-1 ); /*** @ param start * @ param end * @ param stepLength * @ return * @ Author: lulei * @ Description: shortest Path from start to end */public MinStep getMinStep (int start, int end, final HashMap
> StepLength );}

**I. Introduction to method return values**

The Return Value of the above method is a custom data type. The code below shows its specific data structure:

/** [Email protected]: */package com. lulei. distance. bean; import java. util. list; public class MinStep {private boolean reachable; // whether the private int minStep can be reached; // The shortest step size is private List
Step; // Shortest Path public MinStep () {} public MinStep (boolean reachable, int minStep) {this. reachable = reachable; this. minStep = minStep;} public boolean isReachable () {return reachable;} public void setReachable (boolean reachable) {this. reachable = reachable;} public int getMinStep () {return minStep;} public void setMinStep (int minStep) {this. minStep = minStep;} public List
GetStep () {return step;} public void setStep (List
Step) {this. step = step ;}}

The List array of the shortest path stores the nodes that have passed through the shortest path from the start point to the end point.

**2. Optimal previous node for each node**

In the dijela algorithm, we need to save the shortest step from the start point to each node, which is also the step size that needs to be compared in the figure, at the same time, we also need to store the previous node in the step size, so that we can push forward one by one through the end point to the start point, so that we can come up with the complete Optimal Path.

/** [Email protected]: */package com. lulei. distance. bean; public class PreNode {private int preNodeNum; // The first optimal node private int nodeStep; // minimum step public PreNode (int preNodeNum, int nodeStep) {this. preNodeNum = preNodeNum; this. nodeStep = nodeStep;} public int getPreNodeNum () {return preNodeNum;} public void setPreNodeNum (int preNodeNum) {this. preNodeNum = preNodeNum;} public int getNodeStep () {return nodeStep;} public void setNodeStep (int nodeStep) {this. nodeStep = nodeStep ;}}

**Iii. variables that need to be concerned during calculation of the dijela Algorithm**
From the diagram that introduces the dijela algorithm, we know that in the computing process, we need to save the shortest distance from the start point to each node, the nodes that have been computed, and the distance between the two adjacent nodes in the next computing node queue and graph. Let's look at the specific definition through code:

// Key1 node number, key2 node number, value is the step size from key1 to key2 private HashMap
> StepLength; // Number of non-independent nodes private int nodeNum; // remove a node private HashSet
OutNode; // the step from the start point to each point. The key is the target node, and the value is the private HashMap step to the target node.
NodeStep; // The Node private partition list for the next Calculation
NextNode; // start point and end point private int startNode; private int endNode;

Let's take a look at the stepLength attribute. It stores the distance between two adjacent nodes in the graph, such as key1 = 1; key2 = 3; value = 9; this indicates that the distance from node 1 to node 3 is 9. Through this storage, we need to save every two adjacent points in the graph to this type of map.

**Iv. Attribute Initialization**

Before starting the calculation, we need to initialize these attributes as follows:

private void initProperty(int start, int end) {outNode = new HashSet
();nodeStep = new HashMap
();nextNode = new LinkedList
();nextNode.add(start);startNode = start;endNode = end;}

In this step, we need to add the start point to the node queue to be calculated next time.

**V. dijela Algorithm**

This step is the core part of the dijela algorithm. In the computing process, we need to perform the following steps:

**1)**Determine whether the conditions for termination are met. If the conditions for termination are met, end the algorithm. If the conditions for termination are not met, execute the next step. (Conditions for termination: no data in the node queue to be calculated next time or the number of nodes that have been calculated is equal to the total number of nodes)

**2)**Obtain node A of the next computation;

**3)**Obtain the minimum distance from the starting point to the shortest path between nodes;

**4)**Obtain reachable Node B of node A, and determine whether Node B is better than other existing methods to B first from the start point to A. If yes, Node B is updated; otherwise, Node B is not updated;

**5)**Determine whether B is a removed node. If it is not a removed node, add B to the node queue to be calculated next time. Otherwise, no operation is performed;

**6)**Determine whether node A has any node other than Node B. If yes, perform Step 1. Otherwise, execute the next step;

**7)**Remove node A from the node to be computed and add it to the node that has been computed;

**8)**Step 1.

Let's take a look at the specific code implementation:

Private void step () {if (nextNode = null | nextNode. size () <1) {return;} if (outNode. size () = nodeNum) {return;} // obtain the next computing node int start = nextNode. removeFirst (); // The minimum distance to the node: int step = 0; if (nodeStep. containsKey (start) {step = nodeStep. get (start ). getNodeStep ();} // obtain the node's reachable HashMap
NextStep = stepLength. get (start); Iterator
> Iter = nextStep. entrySet (). iterator (); while (iter. hasNext () {Entry
Entry = iter. next (); Integer key = entry. getKey (); // if it is from the start point to the start point, the step size is not calculated. if (key = startNode) {continue ;} // The distance from the start point to the reachable node Integer value = entry. getValue () + step; if ((! NextNode. contains (key ))&&(! OutNode. contains (key) {nextNode. add (key);} if (nodeStep. containsKey (key) {if (value <nodeStep. get (key ). getNodeStep () {nodeStep. put (key, new PreNode (start, value) ;}} else {nodeStep. put (key, new PreNode (start, value) ;}// remove this node from outNode. add (start); // calculate the next node step ();}

**6. Assemble the shortest path and return the result**

Based on the previous calculation, the shortest path from the start point to each node has been calculated. Below we need to assemble the shortest path from the start point to the end point. In this way, the shortest path is calculated, we need to push forward from the end point in sequence, that is, the first node to reach the end point is A, and the first node to reach the short distance of node A is B, until the start point is found to end.

private MinStep changeToMinStep() {MinStep minStep = new MinStep();minStep.setMinStep(nodeStep.get(endNode).getNodeStep());minStep.setReachable(true);LinkedList
step = new LinkedList
();minStep.setStep(step);int nodeNum = endNode;step.addFirst(nodeNum);while (nodeStep.containsKey(nodeNum)) {int node = nodeStep.get(nodeNum).getPreNodeNum();step.addFirst(node);nodeNum = node;}return minStep;}

**VII. Implementation of interface definition methods**
Public MinStep getMinStep (int start, int end, final HashMap
> StepLength) {this. stepLength = stepLength; this. nodeNum = this. stepLength! = Null? This. stepLength. size (): 0; // if (this. stepLength = null | (! This. stepLength. containsKey (start) | (! This. stepLength. containsKey (end) {return UNREACHABLE;} initProperty (start, end); step (); if (nodeStep. containsKey (end) {return changeToMinStep ();} return UNREACHABLE ;}

**8. complete code of the dijela Algorithm**

/** [Email protected]: */package com. lulei. distance. dijkstra; import java. util. hashMap; import java. util. hashSet; import java. util. iterator; import java. util. using list; import java. util. map. entry; import com. lulei. distance. distance; import com. lulei. distance. bean. minStep; import com. lulei. distance. bean. preNode; public class distance1_straimpl implements Distance {// key1 node number, key2 node number, value is the step size private HashMap from key1 to key2
> StepLength; // Number of non-independent nodes private int nodeNum; // remove a node private HashSet
OutNode; // the step from the start point to each point. The key is the target node, and the value is the private HashMap step to the target node.
NodeStep; // The Node private partition list for the next Calculation
NextNode; // start point and end point private int startNode; private int endNode;/*** @ param start * @ param end * @ param stepLength * @ return * @ Author: lulei * @ Description: the shortest distance from start to end */public MinStep getMinStep (int start, int end, final HashMap
> StepLength) {this. stepLength = stepLength; this. nodeNum = this. stepLength! = Null? This. stepLength. size (): 0; // if (this. stepLength = null | (! This. stepLength. containsKey (start) | (! This. stepLength. containsKey (end) {return UNREACHABLE;} initProperty (start, end); step (); if (nodeStep. containsKey (end) {return changeToMinStep ();} return UNREACHABLE;}/*** return the shortest distance and path */private MinStep changeToMinStep () {MinStep minStep = new MinStep (); minStep. setMinStep (nodeStep. get (endNode ). getNodeStep (); minStep. setReachable (true); reset list
Step = new upload list
(); MinStep. setStep (step); int nodeNum = endNode; step. addFirst (nodeNum); while (nodeStep. containsKey (nodeNum) {int node = nodeStep. get (nodeNum ). getPreNodeNum (); step. addFirst (node); nodeNum = node;} return minStep;}/*** @ param start * @ Author: lulei * @ Description: initialization attribute */private void initProperty (int start, int end) {outNode = new HashSet
(); NodeStep = new HashMap
(); NextNode = new vertex list
(); NextNode. add (start); startNode = start; endNode = end;}/*** @ param end * @ Author: lulei * @ Description: */private void step () {if (nextNode = null | nextNode. size () <1) {return;} if (outNode. size () = nodeNum) {return;} // obtain the next computing node int start = nextNode. removeFirst (); // The minimum distance to the node: int step = 0; if (nodeStep. containsKey (start) {step = nodeStep. get (start ). getNodeStep ();} // obtain the node's reachable HashMap
NextStep = stepLength. get (start); Iterator
> Iter = nextStep. entrySet (). iterator (); while (iter. hasNext () {Entry
Entry = iter. next (); Integer key = entry. getKey (); // if it is from the start point to the start point, the step size is not calculated. if (key = startNode) {continue ;} // The distance from the start point to the reachable node Integer value = entry. getValue () + step; if ((! NextNode. contains (key ))&&(! OutNode. contains (key) {nextNode. add (key);} if (nodeStep. containsKey (key) {if (value <nodeStep. get (key ). getNodeStep () {nodeStep. put (key, new PreNode (start, value) ;}} else {nodeStep. put (key, new PreNode (start, value) ;}// remove this node from outNode. add (start); // calculate the next node step ();}}

**Code Testing**

For the above Code test, we still use the example in our example graph to calculate the shortest distance from node 1 to node 5.

/** [email protected]: */ package com.lulei.distance.test; import java.util.HashMap;import com.lulei.distance.Distance;import com.lulei.distance.bean.MinStep;import com.lulei.distance.dijkstra.DistanceDijkstraImpl;import com.lulei.util.JsonUtil; public class DistanceTest {public static void main(String[] args) {// TODO Auto-generated method stub HashMap
> stepLength = new HashMap
>();HashMap
step1 = new HashMap
();stepLength.put(1, step1);step1.put(6, 14);step1.put(3, 9);step1.put(2, 7);HashMap
step2 = new HashMap
();stepLength.put(2, step2);step2.put(1, 7);step2.put(3, 10);step2.put(4, 15);HashMap
step3 = new HashMap
();stepLength.put(3, step3);step3.put(1, 9);step3.put(2, 10);step3.put(4, 11);step3.put(6, 2);HashMap
step4 = new HashMap
();stepLength.put(4, step4);step4.put(2, 15);step4.put(5, 5);step4.put(3, 11);HashMap
step5 = new HashMap
();stepLength.put(5, step5);step5.put(6, 9);step5.put(4, 5);HashMap
step6 = new HashMap
();stepLength.put(6, step6);step6.put(1, 14);step6.put(5, 9);step6.put(3, 2);Distance distance = new DistanceDijkstraImpl();MinStep step = distance.getMinStep(1, 5, stepLength);System.out.println(JsonUtil.parseJson(step));}}

A lot of code is used to assemble the distance between two adjacent nodes. Let's look at the output result:

{"reachable":true,"minStep":20,"step":[1,3,6,5]}

**Last thought**

In real life, the shortest path algorithm has many advantages, such as the maze solution, path planning, and routing addressing. These problems seem complicated, in fact, you only need to do the corresponding conversion and can still use the most basic algorithm to solve the problem.

Recently, I have found that many websites or individuals have reposted their blogs, and I have rejected others' reposts. However, at the very least, you can give me the source of my articles, so that I do not think that my blog has been plagiarized by others. When talking about reprinting, we also need to mention the current Internet environment. Sometimes we can find a blog by ourselves and find it difficult to find the source author or the original link. On the one hand, you do not want to add your own blog address in your blog to describe the quality of your blog. On the other hand, the blogger sometimes modifies errors in the blog, so that others cannot quickly obtain the information.