#include
#include
using namespace std;
#define INFINITY 32767
#define MAX_VEX 50
#define OK 1
#define FALSE 0
#define TRUE 1
#define ERROR -1
bool *visited;
//图的邻接矩阵存储结构
typedef struct {
char *vexs; //动态分配空间存储顶点向量
int arcs[MAX_VEX][MAX_VEX]; //邻接矩阵
int vexnum, arcnum; //图的当前定点数和弧数
}Graph;
//图G 中查找顶点c 的位置
int LocateVex(Graph G, char c) {
for(int i = 0; i
if(G.vexs[i] == c) return i;
}
return ERROR;
}
//创建无向网
void CreateUDN(Graph &G){
//采用数组(邻接矩阵)表示法,构造无向图G
cout
cin >> G.vexnum >> G.arcnum;
cout
G.vexs = (char *) malloc((G.vexnum+1) * sizeof(char));
//构造顶点向量
for(int i = 0; i
cout
cin >> G.vexs[i];
}
G.vexs[G.vexnum] = '\0';
//需要开辟多一个空间存储'\0'
//初始化邻接矩阵
for(int i = 0; i
for( int j = 0; j
G.arcs[i][j] = INFINITY;
cout
char a, b;
int s1, s2;
for(int i = 0; i
cout
cin >> a >> b ;
s1 = LocateVex(G,a); //找到a 和b 在顶点向量中的位置 s2 = LocateVex(G,b);
}
}
//图G 中顶点k 的第一个邻接顶点
int FirstVex(Graph G,int k){
for(int i = 0; i
if (G.arcs[k][i] != INFINITY) return i;
return ERROR;
}
//返回i (相对于j )的下一个邻接顶点
int NextVex(Graph G,int i,int j){
for(int k = j+1; k
if(G.arcs[i][k] != INFINITY) return k;
return ERROR;
}
void DFS(Graph G, int v) {
//从第v 个顶点出发递归地深度优先遍历图G
visited[v] = TRUE;
cout
for(int w = FirstVex(G,v); w >= 0; w = NextVex(G,v,w))
if(!visited[w]) DFS(G,w);
}
//深度优先遍历
void DFSTraverse(Graph G, int i) {
for(int j = 0; j
}
//遍历结点
for(; i
if(!visited[i]) DFS(G,i);
}
//主函数
int main(){
Graph G;
CreateUDN(G);
visited = (bool *) malloc(G.vexnum * sizeof(bool)); cout
DFSTraverse(G,0);
cout
}
#include
#include
using namespace std;
#define INFINITY 32767
#define MAX_VEX 50
#define OK 1
#define FALSE 0
#define TRUE 1
#define ERROR -1
bool *visited;
//图的邻接矩阵存储结构
typedef struct {
char *vexs; //动态分配空间存储顶点向量
int arcs[MAX_VEX][MAX_VEX]; //邻接矩阵
int vexnum, arcnum; //图的当前定点数和弧数
}Graph;
//图G 中查找顶点c 的位置
int LocateVex(Graph G, char c) {
for(int i = 0; i
if(G.vexs[i] == c) return i;
}
return ERROR;
}
//创建无向网
void CreateUDN(Graph &G){
//采用数组(邻接矩阵)表示法,构造无向图G
cout
cin >> G.vexnum >> G.arcnum;
cout
G.vexs = (char *) malloc((G.vexnum+1) * sizeof(char));
//构造顶点向量
for(int i = 0; i
cout
cin >> G.vexs[i];
}
G.vexs[G.vexnum] = '\0';
//需要开辟多一个空间存储'\0'
//初始化邻接矩阵
for(int i = 0; i
for( int j = 0; j
G.arcs[i][j] = INFINITY;
cout
char a, b;
int s1, s2;
for(int i = 0; i
cout
cin >> a >> b ;
s1 = LocateVex(G,a); //找到a 和b 在顶点向量中的位置 s2 = LocateVex(G,b);
}
}
//图G 中顶点k 的第一个邻接顶点
int FirstVex(Graph G,int k){
for(int i = 0; i
if (G.arcs[k][i] != INFINITY) return i;
return ERROR;
}
//返回i (相对于j )的下一个邻接顶点
int NextVex(Graph G,int i,int j){
for(int k = j+1; k
if(G.arcs[i][k] != INFINITY) return k;
return ERROR;
}
void DFS(Graph G, int v) {
//从第v 个顶点出发递归地深度优先遍历图G
visited[v] = TRUE;
cout
for(int w = FirstVex(G,v); w >= 0; w = NextVex(G,v,w))
if(!visited[w]) DFS(G,w);
}
//深度优先遍历
void DFSTraverse(Graph G, int i) {
for(int j = 0; j
}
//遍历结点
for(; i
if(!visited[i]) DFS(G,i);
}
//主函数
int main(){
Graph G;
CreateUDN(G);
visited = (bool *) malloc(G.vexnum * sizeof(bool)); cout
DFSTraverse(G,0);
cout
}