Home Java javaTutorial How to implement topological sorting algorithm using java

How to implement topological sorting algorithm using java

Sep 19, 2023 pm 01:54 PM
java accomplish topological sort

How to implement topological sorting algorithm using java

How to use Java to implement topological sorting algorithm

Topological sorting is a commonly used algorithm in graph theory, used for directed acyclic graph (Directed Acyclic Graph, DAG for short) vertices are sorted. Topological sorting can be used to solve problems such as dependencies or task scheduling. In this article, we will introduce how to use Java to implement the topological sorting algorithm and give corresponding code examples.

The implementation idea of ​​topological sorting is as follows:

  1. First, we need to define a data structure of a directed graph, which can be represented by an adjacency list. An adjacency list is a data structure that stores graphs. Each vertex corresponds to a linked list, and the linked list stores all vertices adjacent to the vertex.
class Graph {
    private int V; // 图的顶点数
    private LinkedList<Integer> adj[]; // 邻接表

    Graph(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i) {
            adj[i] = new LinkedList<>();
        }
    }

    // 添加边
    void addEdge(int v, int w) {
        adj[v].add(w);
    }
}
  1. Then, we need to implement topological sorting method. The implementation process of topological sorting can be divided into two steps:

    a. Traverse the graph, calculate the in-degree of each vertex (that is, how many vertices point to it), and initialize a queue to store the in-degree of 0 the apex.

    b. Continuously take out a vertex from the queue and reduce the in-degree of its adjacent vertices. If the in-degree of a vertex becomes 0, add it to the queue.

    c. Repeat step (b) until the queue is empty and the in-degree of all vertices becomes 0. If the number of vertices enqueued at this time is not equal to the number of vertices of the graph, it means that there is a cycle in the graph and topological sorting cannot be completed.

import java.util.*;

class TopologicalSort {
    // 拓扑排序算法
    void topologicalSort(Graph graph) {
        int V = graph.V;
        LinkedList<Integer> adj[] = graph.adj;

        int[] indegree = new int[V];
        for (int i = 0; i < V; ++i) {
            for (int j : adj[i]) {
                indegree[j]++;
            }
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < V; ++i) {
            if (indegree[i] == 0) {
                queue.add(i);
            }
        }

        int count = 0;
        ArrayList<Integer> result = new ArrayList<>();

        while (!queue.isEmpty()) {
            int u = queue.poll();
            result.add(u);

            for (int v : adj[u]) {
                if (--indegree[v] == 0) {
                    queue.add(v);
                }
            }
            count++;
        }

        if (count != V) {
            System.out.println("图中存在环,无法进行拓扑排序");
            return;
        }

        System.out.println("拓扑排序结果:");
        for (int i : result) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
  1. Finally, we can create a graph and call the topological sort method to sort it.
public class Main {
    public static void main(String[] args) {
        Graph graph = new Graph(6);
        graph.addEdge(5, 2);
        graph.addEdge(5, 0);
        graph.addEdge(4, 0);
        graph.addEdge(4, 1);
        graph.addEdge(2, 3);
        graph.addEdge(3, 1);

        TopologicalSort topologicalSort = new TopologicalSort();
        topologicalSort.topologicalSort(graph);
    }
}

The above are the steps and code examples for using Java to implement the topological sorting algorithm. Through topological sorting algorithms, we can effectively solve problems such as dependencies or task scheduling.

The above is the detailed content of How to implement topological sorting 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1594
276
You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

PS oil paint filter greyed out fix PS oil paint filter greyed out fix Aug 18, 2025 am 01:25 AM

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

Building Cloud-Native Java Applications with Micronaut Building Cloud-Native Java Applications with Micronaut Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

Fixed: Windows Is Showing 'A required privilege is not held by the client' Fixed: Windows Is Showing 'A required privilege is not held by the client' Aug 20, 2025 pm 12:02 PM

RuntheapplicationorcommandasAdministratorbyright-clickingandselecting"Runasadministrator"toensureelevatedprivilegesaregranted.2.CheckUserAccountControl(UAC)settingsbysearchingforUACintheStartmenuandsettingtheslidertothedefaultlevel(secondfr

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

See all articles