/*此程序仅适合强连通图*/
#include<iostream>
#include<string>
using namespace std;
struct ArcNode //定义边表结点
{
int adjvex; //邻接点域,存放该顶点的临界点在顶点表中的下标
ArcNode * next; //为指针域,指向边表中的下一个节点
};
struct VertexNode
{
string vertex; //为数据域,存放顶点信息
ArcNode * firstedge; //为指针域,指向边表中的第一个节点
};
const int MaxSize = 10;
class ALGraph
{
private:
VertexNode adjlist[MaxSize];//存放顶点表的数组
int vertexNum, arcNum; //图的顶点数和边数
int visited[MaxSize];
public:
ALGraph(string a[], int n, int e);
~ALGraph(){}
void DFSTraverse(int v);//深度优先遍历函数
};
ALGraph::ALGraph(string a[], int n, int e)
{
vertexNum = n;
arcNum = e;
for (int i = 0; i < vertexNum; i++)
{
adjlist[i].vertex = a[i];
adjlist[i].firstedge = NULL;
}
for (int k = 0; k < arcNum; k++)
{
int i, j;
cin >> i >> j;
ArcNode * s = new ArcNode;
s->adjvex= j;
s->next = adjlist[i].firstedge;
adjlist[i].firstedge = s;
}
for (int i = 0; i < MaxSize; i++)
{
visited[i] = 0;
}
}
void ALGraph::DFSTraverse(int v)
{
cout<<adjlist[v].vertex <<“\t”;
visited[v] = 1;
ArcNode *p = adjlist[v].firstedge;
while (p != NULL)
{
int j = p->adjvex;
if (visited[j]==0) DFSTraverse(j);
p = p->next;
}
}
int main()
{
string a[4] = { “v0”, “v1”, “v2”, “v3” };
int i, j;
cout << “输入你的图的边数i:”;
cin >> i;
cout << endl;
ALGraph s(a, 4, i);
cout << “输入你想要进行深度遍历的头节点的下标j:”;
cin >> j;
cout << endl;
cout << “深度遍历的结果为:” << endl;
s.DFSTraverse(j);
cout << endl;
return 0;
}