常用图算法(C语言)
Posted huatian5
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用图算法(C语言)相关的知识,希望对你有一定的参考价值。
最短路
Dijkstra
题目:https://leetcode.cn/problems/network-delay-time/description/
邻接矩阵:
int min(int a, int b)
return a < b ? a : b;
int max(int a, int b)
return a < b ? b : a;
int networkDelayTime(int** times, int timesSize, int* timesColSize, int n, int k)
int g[n+1][n+1];
memset(g, 0x3f, sizeof(g));
for (int i = 0; i < timesSize; i++)
int a = times[i][0], b = times[i][1], v = times[i][2];
g[a][b] = v;
int dis[n+1];
int vis[n+1];
memset(vis, 0, sizeof(vis));
memset(dis, 0x3f, sizeof(dis));
dis[k] = 0;
int res = 0;
for (int i = 1; i <= n; i++)
int pos = 0;
for (int j = 1; j <= n; j++)
if (!vis[j] && (pos == 0 || dis[j] < dis[pos]))
pos = j;
vis[pos] = 1;
res = max(res, dis[pos]);
for (int j = 1; j <= n; j++)
dis[j] = min(dis[j], dis[pos] + g[pos][j]);
return res == 0x3f3f3f3f ? -1 : res;
邻接表(链式前向星)
int min(int a, int b)
return a < b ? a : b;
int max(int a, int b)
return a < b ? b : a;
struct node
int to,w,next;
edge[6000 + 5];
int head[100 + 5];
int cnt = 0;
void add_edge(int u, int v, int w)
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
int networkDelayTime(int** times, int timesSize, int* timesColSize, int n, int k)
cnt = 0;
memset(head, -1, sizeof(head));
for (int i = 0; i < timesSize; i++)
int a = times[i][0], b = times[i][1], v = times[i][2];
add_edge(a, b, v);
int dis[n+1];
int vis[n+1];
memset(vis, 0, sizeof(vis));
memset(dis, 0x3f, sizeof(dis));
dis[k] = 0;
int res = 0;
for (int i = 1; i <= n; i++)
int pos = 0;
for (int j = 1; j <= n; j++)
if (!vis[j] && (pos == 0 || dis[j] < dis[pos]))
pos = j;
vis[pos] = 1;
res = max(res, dis[pos]);
for (int j = head[pos]; j != -1; j = edge[j].next)
int y = edge[j].to;
dis[y] = min(dis[y], dis[pos] + edge[j].w);
return res == 0x3f3f3f3f ? -1 : res;
最小生成树
Prim
Kruskal
#define N 1005
struct Edge
int x, y, w;
edge[N*N];
int f[N];
int cmp(struct Edge *a, struct Edge *b)
return a->w - b->w;
int find(int x)
if (f[x] == x)
return f[x];
return f[x] = find(f[x]);
int minCostConnectPoints(int** points, int pointsSize, int* pointsColSize)
// init
for (int i = 0; i <= pointsSize; i++)
f[i] = i;
int cnt = 0;
// construct all edges
for (int i = 0; i < pointsSize; i++)
for (int j = 0; j < pointsSize; j++)
edge[cnt].x = i;
edge[cnt].y = j;
edge[cnt++].w = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
qsort(edge, cnt, sizeof(struct Edge), cmp);
int res = 0, num = 0;
for (int i = 0; i < cnt; i++)
int x = find(edge[i].x);
int y = find(edge[i].y);
if (x == y)
continue;
f[x] = y;
++num;
res += edge[i].w;
if (num == pointsSize - 1)
return res;
return 0;
以上是关于常用图算法(C语言)的主要内容,如果未能解决你的问题,请参考以下文章