c言語でDijkstraアルゴリズムによる最短距離を求める
c言語コード:
#include <stdio.h>
#include <string.h>
int c[101][101],i,j,k,l,n,a,b,u,min;
int dist[101],f[101];
int main()
{
scanf(“%d %d %d", &n, &a, &b);
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
{
c[i][j] = 1000;
}
for (i=1; i<=n; i++)
{
scanf(“%d", &k);
for (j=1; j<=k; j++)
{
scanf(“%d", &l);
if (j==1)
c[i][l] = 0;
else
c[i][l] = 1;
}
}
for (i=1; i<=n; i++)
{
dist[i] = c[a][i];
f[i] = 0;
}
f[a] = 1;
dist[a] = 0;
for (k=0; k<n-1; k++)
{
min = 1000;
u = a;
for (i=1; i<=n; i++)
{
if (!f[i] && dist[i] < min)
{
min = dist[i];
u = i;
}
}
f[u] = 1;
for (i=1; i<=n; i++)
{
if (!f[i] && dist[i] > dist[u] + c[u][i])
dist[i] = dist[u] + c[u][i];
}
}
if (dist[b] >= 1000)
printf(“%d\n",-1);
else
printf(“%d\n",dist[b]);
return 0;
}