Shortest path for a graph in Matlab

Foreword:

The basic concept of graph:

If you want to draw a simple diagram, you can use this website:

Undirected/Directed in the upper left corner is an undirected graph/directed graph  

0-index on the left, 1-index is 0 subscript, 1 subscript.

Node Count is the number of nodes

Graph Data : the name of the initial tail node (a data)

          The name of the two connected nodes and the weight of the connection between the two nodes (three data)

Use matlab to make "graphs":

s and t in Graph refer to the names of vertices in the graph, and the number of elements must be the same, and the data corresponding to s and t will be connected in the structure.

Precautions:

  1. If we use a string in the node name, we need to use curly braces {}, and the character name in the middle needs to be quoted with ''.

2. If the node names are constants, these nodes must all be positive integers starting from 1.

The third element in the Graph is the weight, and the weight corresponds to the lines connecting the nodes.

Directed graph in Matlab :

The function is: digraph()

Weighted adjacency matrix for an undirected graph:

Weighted adjacency matrix for a directed graph:

Algorithm for finding the smallest path: Dijkstra's algorithm:

The blogger previously created an article about Dijkstra when learning data structures: Data Structure - Shortest Path Dijkstra (Dijkstra) Algorithm Explanation and Code Implementation_Dijkstra_Wei&Yan's Blog -CSDN blog can refer to the content inside.

Dijkstra Cons:

How to fix this shortcoming:

What is a negative weight loop?

(Note that a negative weight edge in an undirected graph also belongs to a negative weight circuit, such as the circuit with a weight of -2 between node 3 and node 2 in the figure below.)

There is a function to calculate the shortest path in matlab:

Shortserpath(graph name, start node, end node)

 

Highlight the shortest path in the graph

Highlight(variablename of plot, P accepted in shortestpath, 'EdgeColor', 'color')

Returns the distance matrix between any two points

Find all points within a given range:

after class homework:

Just need to find the shortest path and length. (preferably the shortest path)    

Reference Code: 

%创建图的顶点和边
s = {'v1','v1','v1','v2','v3','v3','v4','v5','v5','v5','v5','v6','v6','v7','v9','v9'};
t = {'v4','v2','v3','v5','v4','v2','v6','v4','v6','v7','v8','v5','v7','v8','v5','v8'};
w = [1,6,3,1,2,2,10,6,4,3,6,10,2,4,2,3];
G = digraph(s,t,w);
myplot = plot(G,'EdgeLabel',G.Edges.Weight,'LineWidth',2);

%求出最短路径
[P,d] = shortestpath (G,'v1','v8')
highlight (myplot,P,'EdgeColor','red')

The blogger once also wrote a blog about data structure diagrams: basic concepts and terminology of diagrams_Wei&Yan's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/weixin_73612682/article/details/132111266