//深搜 邻接矩阵
void DFS(MGraph G, Vertex v)
{
visited[v] = 1;
printf(" %d", v);
for (int i = 0; i < G.vexnum; i++)//G的各个邻接点
{
//判断有没有边
if (G.arcs[v][i] && !visited[i])
DFS(G, i);
}
}
//深搜 邻接表
void DFS(ALGraph *G, int v)
{
visited[v] = 1;
printf(" %d", v);
ArcNode *p = G->vertices[v].firstarc;
while (p)
{
if (!visited[p->adjvex]) DFS(G, p->adjvex);
p = p->nextarc;
}
}
//广搜 邻接矩阵
void BFS(MGraph G, Vertex v)
{
visited[v] = 1;
printf(" %d", v);
int q[10050], front = 0, rear = 0;
q[rear++] = v;
while (rear != front)
{
int now = q[front++];
for (int i = 0; i < G.vexnum; i++)
{
if (G.arcs[now][i] && !visited[i])
{
visited[i] = 1;
printf(" %d", i);
q[rear++] = i;
}
}
}
}
//广搜 邻接表
void BFS(MGraph G, Vertex v)
{
visited[v] = 1;
printf(" %d", v);
int q[10050], front = 0, rear = 0;
q[rear++] = v;
while (rear != front)
{
int now = q[front++];
ArcNode *p = G->vertices[now].firstarc;
while (p)
{
if (!visited[p->adjvex])
{
visited[p->adjvex] = 1;
printf(" %d", p->adjvex);
q[rear++] = p->adjvex;
}
p = p->nextarc;
}
}
}
深搜 广搜 邻接矩阵 邻接表实现函数代码
最新推荐文章于 2022-06-20 16:37:08 发布