# include <stdio.h>
# include <stdlib.h>
# include <iostream>
# include <queue>
# define MAXVEX 20
typedef char VertexType;
using namespace std;
typedef struct EdgeNode {
int adjvex;
struct EdgeNode * next;
} EdgeNode;
typedef struct VertexNode {
VertexType data;
EdgeNode * firstedge;
} VertexNode, AdjList[ MAXVEX] ;
typedef struct {
AdjList adjlist;
int numVertexes, numEdges;
} GraphAdjList;
int get_index ( AdjList arr, char m) {
for ( int i = 0 ; i < MAXVEX; i++ ) {
if ( arr[ i] . data == m)
return i;
}
return - 1 ;
}
void Create ( GraphAdjList & G) {
int i, j, k;
EdgeNode * p;
cout << "请输入顶点数和边数:" << endl;
cin >> G. numVertexes >> G. numEdges;
cout << "输入顶点信息:" << endl;
for ( i = 0 ; i < G. numVertexes; i++ ) {
cin >> G. adjlist[ i] . data;
G. adjlist[ i] . firstedge = NULL ;
}
cout << "输入边(vi,vj)中的下标i,j:" << endl;
for ( k = 0 ; k < G. numEdges; k++ ) {
cin >> i >> j;
p = ( EdgeNode * ) malloc ( sizeof ( EdgeNode) ) ;
p-> adjvex = j;
p-> next = G. adjlist[ i] . firstedge;
G. adjlist[ i] . firstedge = p;
p = p = ( EdgeNode * ) malloc ( sizeof ( EdgeNode) ) ;
p-> adjvex = i;
p-> next = G. adjlist[ j] . firstedge;
G. adjlist[ j] . firstedge = p;
}
}
void print ( GraphAdjList & G) {
cout << "邻接表为:" << endl;
EdgeNode * p;
for ( int i = 0 ; i < G. numVertexes; i++ ) {
p = G. adjlist[ i] . firstedge;
while ( p) {
cout << "<" << G. adjlist[ i] . data << "," << G. adjlist[ p-> adjvex] . data << ">" ;
p = p-> next;
}
cout << endl;
}
}
void dfs ( GraphAdjList & G, int v, int * visited) {
visited[ v] = 1 ;
cout << G. adjlist[ v] . data;
EdgeNode * p = G. adjlist[ v] . firstedge;
while ( p) {
if ( ! visited[ p-> adjvex] )
dfs ( G, p-> adjvex, visited) ;
p = p-> next;
}
return ;
}
void dfsSearch ( GraphAdjList & G, char input) {
int visited[ MAXVEX] = { 0 } ;
for ( int i = 0 ; i < G. numVertexes; i++ ) {
visited[ i] = 0 ;
}
dfs ( G, get_index ( G. adjlist, input) , visited) ;
for ( int i = 0 ; i < G. numVertexes; i++ ) {
if ( ! visited[ i] ) {
dfs ( G, i, visited) ;
}
}
}
void bfs ( GraphAdjList & G, int v, int * visited) {
int u, w;
EdgeNode * p;
queue< int > Q;
cout << G. adjlist[ v] . data;
visited[ v] = 1 ;
Q. push ( v) ;
while ( ! Q. empty ( ) ) {
u = Q. front ( ) ;
Q. pop ( ) ;
p = G. adjlist[ u] . firstedge;
while ( p) {
w = p-> adjvex;
if ( ! visited[ w] ) {
cout << G. adjlist[ w] . data;
visited[ w] = 1 ;
Q. push ( w) ;
}
p = p-> next;
}
}
}
void bfsSearch ( GraphAdjList & G, char input) {
int visited[ MAXVEX] = { 0 } ;
for ( int i = 0 ; i < G. numVertexes; i++ ) {
visited[ i] = 0 ;
}
bfs ( G, get_index ( G. adjlist, input) , visited) ;
for ( int i = 0 ; i < G. numVertexes; i++ ) {
if ( ! visited[ i] ) {
bfs ( G, i, visited) ;
}
}
}
int main ( ) {
GraphAdjList G;
Create ( G) ;
print ( G) ;
cout << "输入深度搜索的起始点:" << endl;
char input;
cin >> input;
dfsSearch ( G, input) ;
cout << endl << "输入广度搜索的起始点:" << endl;
cin >> input;
bfsSearch ( G, input) ;
}
连通图案例
非连通图案例