struct ArcNode
{
int headVex,tailVex; //头尾顶点
ArcNode *headIN,*tailOut;
int weight;
};
struct VexNode
{
int data;
ArcNode *firstIN,*firstOUT;
};
struct Graphic
{
int vexNum,arcNum; //顶点和弧个数
VexNode *NodeArr;
};
void createGraphic(Graphic &g) //创建图
{
cout<<"请输入顶点个数:";
cin>>g.vexNum;
g.NodeArr=new VexNode[g.vexNum];
if (!g.NodeArr)
{
cout<<"顶点数组初始化失败!"<<endl;
return;
}
cout<<"请输入顶点信息:"<<endl;
for (int i=0;i<g.vexNum;i++) //创建顶点
{
int data;
cin>>data;
g.NodeArr[i].data=data;
g.NodeArr[i].firstIN=NULL;
g.NodeArr[i].firstOUT=NULL;
}
//创建边
cout<<"请输入边个数:"<<endl;
cin>>g.arcNum;
for (int i=1;i<=g.arcNum;i++)
{
int tail,head,weight;
int tailIndex,headIndex;
cout<<"弧"<<i<<":";
cin>>tail>>head>>weight;
for (int j=0;j<g.vexNum;j++)
{
if (g.NodeArr[j].data==tail)
{
tailIndex=j;
}
if (g.NodeArr[j].data==head)
{
headIndex=j;
}
}
ArcNode *p=new ArcNode;
p->weight=weight;
p->tailVex=tail;
p->headVex=head;
p->headIN=g.NodeArr[headIndex].firstIN;
p->tailOut=g.NodeArr[tailIndex].firstOUT;
g.NodeArr[headIndex].firstIN=p;
g.NodeArr[tailIndex].firstOUT=p;
}
}
void Printgraph(Graphic &g)
{
cout<<"弧信息输出:"<<endl;
for (int i=0;i<g.vexNum;i++)
{
cout<<"顶点;"<<g.NodeArr[i].data<<" ";
ArcNode *p=g.NodeArr[i].firstOUT;
while(p)
{
cout<<"("<<p->tailVex<<","<<p->headVex<<") "<<p->weight<<" ";
p=p->tailOut;
}
cout<<endl;
}
}
void deleteGraphic(Graphic &g) //删除图
{
for (int i=0;i<g.vexNum;i++)
{
ArcNode *p=g.NodeArr[i].firstIN;
while (p)
{
ArcNode *q=p->headIN;
delete p;
p=q;
}
}
delete []g.NodeArr;
};
void BFS(Graphic &g) //广度优先遍历
{
cout<<"广度优先遍历"<<endl;
bool *visit=new bool[g.vexNum];
for (int i=0;i<g.vexNum;i++)
{
visit[i]=false;
}
std::deque<VexNode *>que;
que.push_front(&(g.NodeArr[0]));
for (int i=0;i<g.vexNum;i++)
{
if (!visit[i])
{
visit[i]=true;
while(que.size())
{
VexNode *p=que.front(); //结点出队列
que.pop_front();
visit[p->data-1]=true;
cout<<p->data<<" ";
//入队列
ArcNode *ap=p->firstOUT;
while (ap)
{
for (int j=0;j<g.vexNum;j++)
{
if (g.NodeArr[j].data==ap->headVex&&!visit[j])
{
que.push_back(&(g.NodeArr[j]));
}
}
ap=ap->tailOut;
}
}
}
}
delete []visit;
}
void DFTCore(Graphic &g,VexNode *node,bool *visit)
{
if (!node)
{
return;
}
visit[node->data-1]=true;
cout<<node->data<<" ";
ArcNode *p=node->firstOUT;
while(p)
{
for (int j=0;j<g.vexNum;j++)
{
if(g.NodeArr[j].data==p->headVex)
{
DFTCore(g,&(g.NodeArr[j]),visit);
}
}
p=p->tailOut;
}
}
void DFT(Graphic &g) //深度优先遍历
{
cout<<"深度优先遍历:"<<endl;
//访问标识
bool *visit=new bool[g.vexNum];
for (int i=0;i<g.vexNum;i++)
{
visit[i]=false;
}
for (int i=0;i<g.vexNum;i++)
{
if (!visit[i])
{
DFTCore(g,&(g.NodeArr[i]),visit);
}
}
delete []visit;
}
int main()
{
// TreeNode *root=NULL;
//CreateTree(root);
//traverse(root);
//cout<<"叶子数量:"<<leafCount(root)<<endl;
//cout<<"高度:"<<height(root)<<endl;
//cengxubianli(root);
Graphic g;
createGraphic(g);
//创建图
Printgraph(g);
BFS(g);
DFT(g);
deleteGraphic(g);
system("pause");
return 0;
}