您的位置:首页 > 其它

链式存储无向图的基本操作

2016-07-20 21:29 543 查看
首先声明定义之后会用到的宏

typedef char     VertexType;
typedef int      EdgeType;
#define INF      65535
#define MAXVEX   100
bool visited[MAXVEX];


链式存储结构

typedef struct EdgeNode
{
int adjvex;
EdgeType weight;
EdgeNode *next;
} EdgeNode;
typedef struct VextexNode
{
VertexType data;
EdgeNode *firstedge;
} VextexNode, AdjList[MAXVEX];
typedef struct GraphAdjList
{
AdjList adjList;
int vexter_num, edge_num;
} GraphAdjList;


创建初始化图

void create_algraph(GraphAdjList *G)
{
EdgeNode *e;
cin >> G->vexter_num >> G->edge_num;
for(int i = 0; i < G->vexter_num; ++ i)
{
cin >> G->adjList[i].data;
G->adjList[i].firstedge = NULL;
}
for(int i = 0; i < G->edge_num; ++ i)
{
int v_s, v_e;
cin >> v_s >> v_e;
e = new EdgeNode;
e->adjvex = v_e;
e->next = G->adjList[v_s].firstedge;
G->adjList[v_s].firstedge = e;

e = new EdgeNode;
e->adjvex = v_s;
e->next = G->adjList[v_e].firstedge;
G->adjList[v_e].firstedge = e;
}
}


链式存储无向图 递归深度优先遍历

void DFS(GraphAdjList *G, int i)
{
visited[i] = true;
cout << G->adjList[i].data << " ";
EdgeNode *p;
p = G->adjList[i].firstedge;
while(p)
{
if(!visited[p->adjvex])
DFS(G, p->adjvex);
p = p->next;
}
}
void DFS_Traverse(GraphAdjList *G)
{
for(int i = 0; i < G->vexter_num; ++ i)
visited[i] = false;
for(int i = 0; i < G->vexter_num; ++ i)
if(!visited[i])
DFS(G, i);
}


链式存储无向图广度优先遍历

void BFSTraverse(GraphAdjList *G)
{
for(int i = 0; i < G->vexter_num; ++ i)
visited[i] = false;
queue<int> Q;
EdgeNode *p;
for(int i = 0; i < G->vexter_num; ++ i) {
if(!visited[i]) {
visited[i] = true;
cout << G->adjList[i].data << " ";
Q.push(i);
while(!Q.empty()) {
int k = Q.front();
Q.pop();
p = G->adjList[k].firstedge;
while(p) {
if(!visited[p->adjvex]) {
visited[p->adjvex] = true;
cout << G->adjList[p->adjvex].data << " ";
Q.push(p->adjvex);
p = p->next;
}
else {
p = p->next;
}
}
}
}
}
}


测试

int main()
{
/*
5 6
A B C D E
0 1
1 2
0 4
2 4
0 3
2 3
*/
GraphAdjList *GL = new GraphAdjList;
create_algraph(GL);
DFS_Traverse(GL);
cout << endl;
BFSTraverse(GL);
cout << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  结构 图-遍历