Problem A: 数据结构:图的邻接矩阵存储基本操作

Problem A: 数据结构:图的邻接矩阵存储基本操作

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 5731  Solved: 3789
[Submit] [Status] [Web Board] [Creator:]

Description

邻接矩阵是图的一种存储结构,深入理解其实现的含义。阅读主函数、邻接矩阵存储的图的输出、求顶点在图中的位置等相关代码,完成邻接矩阵连通的无向图的创建、深度优先搜索、广度优先搜索。

Input

输入1,输出图中的顶点信息和邻接矩阵;

输入2,代表创建无向图,然后输入n和m,表示图的顶点和边的数量,接着输入n个字符表示顶点的意义,然后输入m行,每行由x和y构成,代表顶点x和y有一条边相连;

输入3,代表深度遍历图,后面输入字符x,表示从顶点x 进行深度优先遍历;

输入4,代表广度遍历图,后面输入字符x,表示从顶点x 进行广度优先遍历。

Output

按照输入的顺序依次输出相关信息

Sample Input Copy

2
4 4
a b c d
a b
a c
b c
c d
1
3 a
4 c

Sample Output Copy

abcd
0110
1010
1101
0010
abcd
cabd

HINT

#include <iostream>
using namespace std;

#define MVNum 20   //假设当前顶点数最多为20个
int visited[MVNum];//用来存放当前顶点是否遍历过

//*****定义邻接矩阵****
typedef char VerTexType;
typedef int ArcType;
typedef struct
{
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum,arcnum;
}AMGraph;

//输出图的邻接矩阵
void PrintAMGraph(AMGraph MG){
int i,j;
if(MG.vexnum<=0)
return;

for(i=0; i<MG.vexnum; i++)
cout<<MG.vexs[i];
cout<<endl;

for(i=0; i<MG.vexnum; i++){
for(j=0; j<MG.vexnum; j++)
cout<<MG.arcs[i][j];
cout<<endl;
}
}

//若G中存在v,则返回该顶点在图中位置,否则返回-1
int LocateVex(AMGraph G, char v)
{
int i;
for(i=0; i<G.vexnum; i++)
{
    if(G.vexs[i]==v)
        return i;
}
return -1;
}

//返回顶点v的第一个临接点位置,否则返回-1
int FisrtAdjVertex(AMGraph G, int v)
{
//--------补充代码--Start------


//--------补充代码--End-------
}

//返回顶点v相对于w的下一个临接点位置,否则返回-1
int NextAdjVertex(AMGraph G, int v, int w)
{
//--------补充代码--Start------


//--------补充代码--End-------
}

//邻接矩阵存储方式建立无向图
void CreateAMGraph(AMGraph &G)
{
/*
step 1.输入图中顶点总数与边的总数
step 2.输入图中顶点信息,存放到G.vexs[i]数组中
step 3.初始化邻接矩阵中所有值为0
step 4.输入边的信息,修改邻接矩阵中相对应的元素值
*/
//--------补充代码--Start------


//--------补充代码--End-------
}

//从第i个顶点开始深度遍历
void DFSAMGraph(AMGraph G,int i)
{
//--------补充代码--Start------

//--------补充代码--End-------
}

//从第i个顶点开始广度遍历
void BFSAMGraph(AMGraph G,int i)
{
//--------补充代码--Start------

//--------补充代码--End-------
}
/*
4 4
a b c d
a b
a c
b c
c d
*/
//主函数
int main()
{
int i,select,vex;
char start;
AMGraph MG;
MG.vexnum=MG.arcnum=0;

while(cin>>select)
{
if(select==1){//输出图
PrintAMGraph(MG);
}
else if(select==2){//建立无向图
CreateAMGraph(MG);
}
else if(select==3){//深度遍历
getchar();
cin>>start;//遍历的起始顶点
vex = LocateVex(MG, start);
for(i=0; i<MG.vexnum; i++)
visited[i] = 0;
DFSAMGraph(MG,vex);
cout<<endl;
}
else if(select==4){//广度遍历
getchar();
cin>>start;//遍历的起始顶点
vex = LocateVex(MG, start);
for(i=0; i<MG.vexnum; i++)
visited[i] = 0;
BFSAMGraph(MG,vex);
cout<<endl;
}
}
return 0;
}