search
HomeBackend DevelopmentC#.Net TutorialHow to implement the shortest path algorithm in C#

How to implement the shortest path algorithm in C#

Sep 19, 2023 am 11:34 AM
Implementationshortest path algorithmc#programming

How to implement the shortest path algorithm in C#

How to implement the shortest path algorithm in C# requires specific code examples

The shortest path algorithm is an important algorithm in graph theory, used to solve a graph The shortest path between two vertices. In this article, we will introduce how to use C# language to implement two classic shortest path algorithms: Dijkstra algorithm and Bellman-Ford algorithm.

Dijkstra's algorithm is a widely used single-source shortest path algorithm. Its basic idea is to start from the starting vertex, gradually expand to other nodes, and update the shortest path of the discovered nodes. The following is a sample code that uses Dijkstra's algorithm to solve the shortest path:

using System;
using System.Collections.Generic;

public class DijkstraAlgorithm
{
    private int vertexCount;
    private int[] distance;
    private bool[] visited;
    private List<List<int>> adjacencyMatrix;

    public DijkstraAlgorithm(List<List<int>> graph)
    {
        vertexCount = graph.Count;
        distance = new int[vertexCount];
        visited = new bool[vertexCount];
        adjacencyMatrix = graph;
    }

    public void FindShortestPath(int startVertex)
    {
        // 初始化距离数组和访问数组
        for (int i = 0; i < vertexCount; i++)
        {
            distance[i] = int.MaxValue;
            visited[i] = false;
        }

        // 起始顶点到自身的距离为0
        distance[startVertex] = 0;

        for (int i = 0; i < vertexCount - 1; i++)
        {
            int u = FindMinDistance();

            // 标记u为已访问
            visited[u] = true;

            // 更新u的邻接顶点的距离
            for (int v = 0; v < vertexCount; v++)
            {
                if (!visited[v] && adjacencyMatrix[u][v] != 0 && distance[u] != int.MaxValue
                    && distance[u] + adjacencyMatrix[u][v] < distance[v])
                {
                    distance[v] = distance[u] + adjacencyMatrix[u][v];
                }
            }
        }

        // 输出最短路径
        Console.WriteLine("顶点    最短路径");
        for (int i = 0; i < vertexCount; i++)
        {
            Console.WriteLine(i + "    " + distance[i]);
        }
    }

    private int FindMinDistance()
    {
        int minDistance = int.MaxValue;
        int minDistanceIndex = -1;
        for (int i = 0; i < vertexCount; i++)
        {
            if (!visited[i] && distance[i] <= minDistance)
            {
                minDistance = distance[i];
                minDistanceIndex = i;
            }
        }
        return minDistanceIndex;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // 构建示例图
        List<List<int>> graph = new List<List<int>>()
        {
            new List<int>() {0, 4, 0, 0, 0, 0, 0, 8, 0},
            new List<int>() {4, 0, 8, 0, 0, 0, 0, 11, 0},
            new List<int>() {0, 8, 0, 7, 0, 4, 0, 0, 2},
            new List<int>() {0, 0, 7, 0, 9, 14, 0, 0, 0},
            new List<int>() {0, 0, 0, 9, 0, 10, 0, 0, 0},
            new List<int>() {0, 0, 4, 0, 10, 0, 2, 0, 0},
            new List<int>() {0, 0, 0, 14, 0, 2, 0, 1, 6},
            new List<int>() {8, 11, 0, 0, 0, 0, 1, 0, 7},
            new List<int>() {0, 0, 2, 0, 0, 0, 6, 7, 0}
        };

        // 使用Dijkstra算法求解最短路径
        DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm(graph);
        dijkstraAlgorithm.FindShortestPath(0);
    }
}

The Bellman-Ford algorithm is an algorithm for solving the shortest path problem with negative weight graphs. It uses the idea of ​​dynamic programming to gradually update the shortest path of the vertices. The following is a sample code that uses the Bellman-Ford algorithm to solve the shortest path:

using System;
using System.Collections.Generic;

public class BellmanFordAlgorithm
{
    private int vertexCount;
    private int[] distance;
    private List<Edge> edges;

    private class Edge
    {
        public int source;
        public int destination;
        public int weight;

        public Edge(int source, int destination, int weight)
        {
            this.source = source;
            this.destination = destination;
            this.weight = weight;
        }
    }

    public BellmanFordAlgorithm(int vertexCount)
    {
        this.vertexCount = vertexCount;
        distance = new int[vertexCount];
        edges = new List<Edge>();
    }

    public void AddEdge(int source, int destination, int weight)
    {
        edges.Add(new Edge(source, destination, weight));
    }

    public void FindShortestPath(int startVertex)
    {
        // 初始化距离数组
        for (int i = 0; i < vertexCount; i++)
        {
            distance[i] = int.MaxValue;
        }

        // 起始顶点到自身的距离为0
        distance[startVertex] = 0;

        // 迭代vertexCount-1次,更新距离
        for (int i = 0; i < vertexCount - 1; i++)
        {
            foreach (Edge edge in edges)
            {
                if (distance[edge.source] != int.MaxValue && distance[edge.source] + edge.weight < distance[edge.destination])
                {
                    distance[edge.destination] = distance[edge.source] + edge.weight;
                }
            }
        }

        // 检查是否存在负权环路
        foreach (Edge edge in edges)
        {
            if (distance[edge.source] != int.MaxValue && distance[edge.source] + edge.weight < distance[edge.destination])
            {
                Console.WriteLine("图中存在负权环路");
                return;
            }
        }

        // 输出最短路径
        Console.WriteLine("顶点    最短路径");
        for (int i = 0; i < vertexCount; i++)
        {
            Console.WriteLine(i + "    " + distance[i]);
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // 构建示例图
        int vertexCount = 5;
        BellmanFordAlgorithm bellmanFordAlgorithm = new BellmanFordAlgorithm(vertexCount);
        bellmanFordAlgorithm.AddEdge(0, 1, 6);
        bellmanFordAlgorithm.AddEdge(0, 2, 7);
        bellmanFordAlgorithm.AddEdge(1, 2, 8);
        bellmanFordAlgorithm.AddEdge(1, 4, -4);
        bellmanFordAlgorithm.AddEdge(1, 3, 5);
        bellmanFordAlgorithm.AddEdge(2, 4, 9);
        bellmanFordAlgorithm.AddEdge(2, 3, -3);
        bellmanFordAlgorithm.AddEdge(3, 1, -2);
        bellmanFordAlgorithm.AddEdge(4, 3, 7);

        // 使用Bellman-Ford算法求解最短路径
        bellmanFordAlgorithm.FindShortestPath(0);
    }
}

The above is a sample code that uses the C# language to implement the Dijkstra algorithm and the Bellman-Ford algorithm. With these two algorithms, we can solve the shortest path problem in the graph.

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

Statement
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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment