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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to write a time series forecasting algorithm using C# Time series forecasting is a method of predicting future data trends by analyzing past data. It has wide applications in many fields such as finance, sales and weather forecasting. In this article, we will introduce how to write time series forecasting algorithms using C#, with specific code examples. Data Preparation Before performing time series forecasting, you first need to prepare the data. Generally speaking, time series data should be of sufficient length and arranged in chronological order. You can get it from the database or

How to implement the greedy algorithm in C# The greedy algorithm (Greedy algorithm) is a commonly used problem-solving method. It selects the current optimal solution every time in the hope of obtaining the global optimal solution. In C#, we can use greedy algorithms to solve many practical problems. This article will introduce how to implement the greedy algorithm in C# and provide specific code examples. 1. Basic principles of greedy algorithm The basic idea of greedy algorithm is to choose the current optimal solution every time, regardless of the possible impact of subsequent steps. This kind of thinking

How to use C# to write deep learning algorithms Introduction: With the rapid development of artificial intelligence, deep learning technology has achieved breakthrough results in many fields. In order to implement the writing and application of deep learning algorithms, the most commonly used language currently is Python. However, for developers who prefer to use the C# language, it is also feasible to use C# to write deep learning algorithms. This article will introduce how to write deep learning algorithms using C# and provide specific code examples. 1. Create a C# project. Before starting to write a deep learning algorithm, you first need to create

How to use C# to write a breadth-first search algorithm Breadth-First Search (BFS) is a commonly used graph search algorithm that is used to traverse a graph or tree according to breadth. In this article, we will explore how to write a breadth-first search algorithm using C# and provide concrete code examples. Algorithm Principle The basic principle of the breadth-first search algorithm is to start from the starting point of the algorithm and expand the search range layer by layer until the target is found or the entire graph is traversed. It is usually implemented through queues.

Polling in Android is a key technology that allows applications to retrieve and update information from a server or data source at regular intervals. By implementing polling, developers can ensure real-time data synchronization and provide the latest content to users. It involves sending regular requests to a server or data source and getting the latest information. Android provides multiple mechanisms such as timers, threads, and background services to complete polling efficiently. This enables developers to design responsive and dynamic applications that stay in sync with remote data sources. This article explores how to implement polling in Android. It covers the key considerations and steps involved in implementing this functionality. Polling The process of periodically checking for updates and retrieving data from a server or source is called polling in Android. pass

How to implement PHP image filter effects requires specific code examples. Introduction: In the process of web development, image filter effects are often used to enhance the vividness and visual effects of images. The PHP language provides a series of functions and methods to achieve various picture filter effects. This article will introduce some commonly used picture filter effects and their implementation methods, and provide specific code examples. 1. Brightness adjustment Brightness adjustment is a common picture filter effect, which can change the lightness and darkness of the picture. By using imagefilte in PHP

How to write Huffman coding algorithm using C# Introduction: Huffman coding algorithm is a lossless algorithm used for data compression. During data transmission or storage, data is effectively compressed by using shorter codes for more frequent characters and longer codes for less frequent characters. This article will introduce how to use C# to write the Huffman coding algorithm and provide specific code examples. The basic principle of Huffman coding algorithm The core idea of Huffman coding algorithm is to construct a Huffman tree. First, by counting the frequency of character occurrences, the

How to use C# to write a quick sort algorithm. The quick sort algorithm is an efficient sorting algorithm. Its idea is to divide the array into smaller sub-problems through the idea of divide and conquer, then recursively solve these sub-problems, and finally merge them to get The answer to the entire problem. Below we will introduce in detail how to use C# to write a quick sort algorithm and give relevant code examples. Algorithm idea The idea of quick sorting can be summarized into the following three steps: select a benchmark element, usually the first element of the array;
