图的存储结构
邻接表的定义
typedef struct Arcnode
{
int adjvex;//边所指向的结点的位置
struct Arcnode *nextarc;//指向下一条边的指针
int info;
}Arcnode;
typedef struct
{
char data;//顶点信息
Arcnode *firstarc;//顶点所指向的下一个边
}Vnode;
typedef struct
{
Vnode adjlist[maxsize];
int n,e;
}AGraph;//图的邻接表类型
深度优先遍历
int visit[maxsize]
void DFS(AGraph *G,int v)
{
Arcnode *p;
visit[v]=1;
Visit(v);
p=G->adjlist[v].fistarc;
while(p!=NULL)
{
if(visit[p->adjvex]==0)
DFS(G,p->adjvex);
p=p->nextarc;
}
}
图的广度优先遍历
void BFS(AGrpha *G,int v,int visit[maxsize])
{
Arcnode *p;
int que[maxsiez],front=0.rear=0;
int j;
Visit(v);
rear=(rear+1)%maxsize;
que[rear]=v;
while(front!=rear)
{
front=(front+1)%maxsize;
j=que[front];
p=G->adjlist[j].fistarc;
while(p!=NULL)
{
if(visit[p->adjvex]==0)
{
Visit(p->adjvex);
visit[p->adjvex]=1;
rear=(rear+1)%maxsize;
que[rear]=p->adjvex;
}
p=p->nextarc;
}
}
}
最短路径
迪杰斯特拉算法
void Dijkstra(Mgraph g,int v,int dist[],int path[])
{
int set[maxsize];
int min,i,j,u;
for(i=0,i<g.n,i++)
{
set[i]=0;
dist[i]=g.edges[v][i];
if(g.edges[v][i]<INF)
path[i]=v;
else
path[i]=-1;
}
set[v]=1;
path[v]=-1
for(i=0;i<g.n-1;i++)
{
min=INF;
for(j=0;j<g.n;i++)
{
if(set[j]==0&&dist[j]<min)
{
u=j;
min=dist[j]
}
}
set[u]=1;
for(i=0;i<g.n;++i)
{
if(set[i]==0&&dist[u]+g.edges[u][i]<dist[i])
dist[i]=dist[u]+g.edges[u][i];
path[i]=u;
}
}
}
拓扑排序
typedef struct
{
int data;
int count;
Arcnode *firstarc;
}Vnode;
int Topsort(Agraph *G)
{
int i,j,n=o;
int stack[maxsize],top=-1;
Arcnode *p;
for(i=0;i<G->n;++i)
{
if(G->adjlist[i].count==0)
stack[++top]=i;
}
while(top!=-1)
{
i=stack[top--];
++n;
count<<i<<" ";
p=G->adjlist[i].firstarc;
while(p!=NULL)
{
j=p->adjvex;
--(G->adjlist[j].count);
if(G->adjlist[j].count)==)
stack[+top]=j;
p=p->nextarc;
}
}
if(n==G->n)
return 1;
else
return 0;
}