1.cè¯è¨ç¼å路线
cè¯è¨ç¼å路线
#include <stdio.h>
#include <malloc.h>
#include<stdlib.h>
#define MAX
#define MAXNUM
int previous[MAX-1];// æ±è·¯å¾éè¦
int pp[MAX-1];// è®°å½æçè·¯å¾
typedef struct graphnode
{
int vexnum; //顶ç¹
int arcnum; //弧
int gra[MAX][MAX]; //é»æ¥ç©éµè¡¨ç¤º0æ1
}Graph;
int dist[MAX]; // æçè·ç¦»
int arc[MAX][MAX]; // æ
int main()
{
void Dijkstra(Graph *g,源码牛牛岛源码int v);
int i,j,n,m;
int v; //æºç¹
Graph *G;
G=(Graph *)malloc(sizeof(Graph));
printf("vexnum:\n");
scanf("%d",&G->vexnum);
printf("arcnum:\n");
scanf("%d",&G->arcnum);
printf("graph:\n");
for(i=0;i<G->vexnum;i++)
for(j=0;j<G->vexnum;j++)
{
scanf("%d",&G->gra[i][j]);
}
for(i=0;i<G->vexnum;i++)
for(j=0;j<G->vexnum;j++)
{
if(G->gra[i][j]==1)
{
printf("请è¾å ¥%då°%dçæå¼:",i,j);
scanf("%d",&arc[i][j]);//è¥æ弧 åè¾å ¥iå°jç´æ¥çæ
}
else
arc[i][j]=MAXNUM;
}
printf("请è¾å ¥æºç¹vçå¼:");
scanf("%d",&v);
Dijkstra(G,v);
printf("请è¾å ¥æºç¹æè¦å°è¾¾çç¹ï¼\n");
scanf("%d",&n);
pp[0]=0;
i=1;
m=n;// è®°å½nçå¼
while(n!=0)// æ±0å°å ¶ä»ç¹è·¯å¾
{
pp[i]=previous[n];
i++;
n=previous[n];
}
printf("Path:0 -> ");
for(j=G->vexnum-1;j>=0;j--)
if(pp[j]!=0)
printf(" %d -> ",pp[j]);
printf("%d\n",m);
return 0;
}
void Dijkstra(Graph *G,int v)
{
int previous[MAX-1];
int newdist;
bool sign[MAX];
if(v<0||v>MAX-1)
{
printf("该æºç¹ä¸åå¨ï¼\n");
return;
}
for(int i=0;i<G->vexnum;i++) //åå§å
{
dist[i]=arc[v][i];
sign[i]=false;
if(dist[i]==MAXNUM)
previous[i]=0;
else
previous[i]=v;
}
dist[v]=0;
sign[v]=true;
for(i=0;i<G->vexnum;i++) // i<n-1 å¾ å®
{
float temp=MAXNUM;
int u=v; //u ä¸é´åé
for(int j=0;j<G->vexnum;j++)
if((!sign[j])&&(dist[j]<temp))
{
u=j;
temp=dist[j];
}
sign[u]=true;
for(j=0;j<G->vexnum;j++)
if((!sign[j])&&(arc[u][j]<MAXNUM))
{
newdist=dist[u]+arc[u][j];
if(newdist<dist[j])
{
dist[j]=newdist;
previous[j]=u;
}
}
}
for(i=0;i<G->vexnum;i++)
if(dist[i]!=MAXNUM)
printf("ä»%då°%dçæçè·¯å¾æ¯ %d\n",v,i,dist[i]);
else
printf("ä»%då°%dæ æçè·¯å¾\n",v,i);
printf("\n");
}
è¿æ¯Dijkstraç®æ³æ±åæºæçè·¯å¾ç®æ³ ä¸ç¨åºä¸ åå®é¡¶ç¹ä»0å¼å§ï¼æç´¢æ´ä¸ªå¾ï¼ç¶åæ±åº0å°å ¶ä»åç¹çæçè·ç¦»ï¼åæ¾å¨distæ°ç»ä¸ï¼mainå½æ°åé¢å è¡æ¯æ±0å°å ¶ä»åç¹çè·¯å¾ åºæ¬ä¸è½æ»¡è¶³ä½ çè¦æ±äº
2024-11-19 02:27
2024-11-19 01:52
2024-11-19 01:31
2024-11-19 01:25
2024-11-19 01:15
2024-11-19 00:38
2024-11-19 00:23
2024-11-19 00:04