Home Java javaTutorial How to implement the shortest path algorithm using java

How to implement the shortest path algorithm using java

Sep 19, 2023 am 08:18 AM
java algorithm shortest path

How to implement the shortest path algorithm using java

How to use Java to implement the shortest path algorithm

Overview:
The shortest path algorithm is an important application in graph theory, in the fields of network routing, map navigation, etc. All have a wide range of applications. In this article, we will learn how to implement the shortest path algorithm using Java and provide concrete code examples.

Algorithm ideas:
There are many ways to implement the shortest path algorithm, among which the two most famous algorithms are Dijkstra algorithm and A* algorithm. Here we will focus on the implementation of Dijkstra's algorithm.

The basic idea of ​​Dijkstra's algorithm is to start from a starting node and calculate the shortest paths to all other nodes in sequence. The specific algorithm process is as follows:

  1. Create a distance array dist to store the shortest distance from the starting node to other nodes. Initially, set the distance of the starting node to 0 and the distance of other nodes. Set to infinity.
  2. Create a collection visited to store the nodes for which the shortest path has been calculated.
  3. Repeat the following steps until all nodes have been visited:
    a. Find the unvisited node closest to the starting node in the distance array dist, and add the node to the visited set.
    b. Update the distance array dist. If a shorter path to other nodes can be found through the current node, update the distance of the node.
  4. According to the final distance array dist, the shortest path from the starting node to other nodes can be obtained.

Code implementation:
The following is a code example to implement the Dijkstra algorithm using Java:

import java.util.*;

public class DijkstraAlgorithm {

    public static void dijkstra(int[][] graph, int start) {
        int numNodes = graph.length;

        int[] dist = new int[numNodes];
        boolean[] visited = new boolean[numNodes];

        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[start] = 0;

        for (int i = 0; i < numNodes; i++) {
            int minDist = Integer.MAX_VALUE;
            int minIndex = -1;

            for (int j = 0; j < numNodes; j++) {
                if (!visited[j] && dist[j] < minDist) {
                    minDist = dist[j];
                    minIndex = j;
                }
            }

            visited[minIndex] = true;

            for (int j = 0; j < numNodes; j++) {
                if (!visited[j] && graph[minIndex][j] != 0 && dist[minIndex] != Integer.MAX_VALUE
                        && dist[minIndex] + graph[minIndex][j] < dist[j]) {
                    dist[j] = dist[minIndex] + graph[minIndex][j];
                }
            }
        }

        printResult(dist);
    }

    public static void printResult(int[] dist) {
        int numNodes = dist.length;

        System.out.println("最短路径距离:");
        for (int i = 0; i < numNodes; i++) {
            System.out.println("节点 " + i + " 的最短路径距离是 " + dist[i]);
        }
    }

    public static void main(String[] args) {
        int[][] graph = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                          { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                          { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                          { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                          { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                          { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
                          { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
                          { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                          { 0, 0, 2, 0, 0, 0, 6, 7, 0 }
                        };

        int startNode = 0;

        dijkstra(graph, startNode);
    }
}
Copy after login

In the above code, we created a class named DijkstraAlgorithm. The dijkstra method is a key part of implementing the Dijkstra algorithm. In the main method, we define a 9x9 two-dimensional array graph to represent the adjacency matrix of the graph, and specify the starting node as 0. By calling the dijkstra method, we can get the shortest path distance from the starting node to other nodes.

Summary:
Using Java to implement the shortest path algorithm is a very interesting task with practical application value. By learning the basic ideas and specific implementation code of Dijkstra's algorithm, we can better understand the principles of the shortest path algorithm and flexibly apply it in actual projects. I hope the code examples provided in this article will help you understand and use the shortest path algorithm.

The above is the detailed content of How to implement the shortest path algorithm using java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles