dijkstra最短路徑演算法C實現

2021-05-23 13:01:51 字數 2508 閱讀 6772

//path記錄上乙個節點

# include

# include

# define maxlen 10

# define large 999

typedef struct

int vexnum;

char vexs[maxlen];

int arcs[maxlen][maxlen];

}graph;

void init_graph(graph *g)

int i = 0,j = 0;

g -> vexnum = 5;

for(i = 0; i < 5; i++)

for(j = 0; j < 5; j++)

g -> arcs[i][j] = 1000;

g -> arcs[0][1] = 1;

g -> arcs[1][0] = 1;

g -> arcs[0][3] = 6;

g -> arcs[3][0] = 6;

g -> arcs[0][4] = 7;

g -> arcs[4][0] = 7;

g -> arcs[1][2] = 2;

g -> arcs[2][1] = 2;

g -> arcs[2][3] = 2;

g -> arcs[3][2] = 2;

g -> arcs[1][3] = 2;

g -> arcs[3][1] = 2;

g -> arcs[2][4] = 2;

g -> arcs[4][2] = 2;

g -> arcs[3][4] = 5;

g -> arcs[4][3] = 5;

//g -> arcs[3][2] = 3;

//g -> arcs[3][1] = 1;

g -> vexs[0] = 'a';

g -> vexs[1] = 'b';

g -> vexs[2] = 'c';

g -> vexs[3] = 'd';

g -> vexs[4] = 'e';

void shortpath_dijkstra(graph g)

int cost[maxlen][maxlen];//cost[i][j]: the cost of i to j.

int dist[maxlen];//dist[i]: the distance of source point to i.

int path[maxlen];//the point passed by.

int s[maxlen];//if s[i] = 1,then i is in the source point gather.

int i,j,v0,min,u;

printf("input the source point(1 means the first point):");

scanf("%d",&v0);

v0--;

for(i = 0; i < g.vexnum; i++)

for(j = 0; j < g.vexnum; j++)

cost[i][j] = g.arcs[i][j];

for(i = 0; i < g.vexnum; i++)

dist[i] = cost[v0][i];

if(dist[i] < large && dist[i] > 0)

path[i] = v0;

s[i] = 0;

s[v0] = 1;

for(i = 0; i < g.vexnum; i++)

min = large;

u = v0;

for(j = 0; j < g.vexnum; j++)

if(s[j] == 0 && dist[j] < min)

min = dist[j];

u = j;

s[u] = 1;

for(j = 0; j < g.vexnum; j++)

if(s[j] == 0 && dist[u] + cost[u][j] < dist[j])

dist[j] = dist[u] + cost[u][j];

path[j] = u;

printf("output%d/n/n",v0);

for(i = 0; i < g.vexnum; i++)

if(s[i] == 1)

u = i;

while(u != v0)

printf(" %c <- ",g.vexs[u]);

u = path[u];

printf(" %c ",g.vexs[u]);

printf(" :%d /n",dist[i]);

else printf(" %c <- %c: no path /n",g.vexs[i],g.vexs[v0]);

int main()

graph g;

init_graph(&g);

shortpath_dijkstra(g);

return 0;

Dijkstra最短路徑演算法

基本思路是 選擇出發點相鄰的所有節點中,權最小的乙個,將它的路徑設定為確定。其他節點的路徑需要儲存起來。然後從剛剛確認的那個節點的相鄰節點,算得那些節點的路徑長。然後從所有未確定的節點中選擇乙個路徑最短的設定為確定。重複上面步驟即可。void dijkstra graph g,string v fl...

Dijkstra最短路徑演算法

引入 dijkstra 迪傑斯特拉 演算法是典型的最短路徑路由演算法,用於計算乙個節點到其他所有節點的最短路徑。主要特點是以起始點為中心向外層層擴充套件,直到擴充套件到終點為止。dijkstra演算法能得出最短路徑的最優解,但由於它遍歷計算的節點很多,所以效率低。package dijkstra p...

最短路徑 Dijkstra演算法

最短路徑 描述 已知乙個城市的交通路線,經常要求從某一點出發到各地方的最短路徑。例如有如下交通圖 則從a出發到各點的最短路徑分別為 b 0c 10 d 50 e 30 f 60 輸入 輸入只有乙個用例,第一行包括若干個字元,分別表示各頂點的名稱,接下來是乙個非負的整數方陣,方陣維數等於頂點數,其中0...