学习图的第一步 :
#define MAXNODE 40 // 千万不要加 ;
#define NIL 999
#define INFI 9999999
#include <iostream>
#include <queue>
using namespace std;
struct arcnode {
int vertex;
int weight;
struct arcnode * nextarc;
};
typedef struct {
int vertex;
struct arcnode * firstarc;
} vernode;
queue<int> gqueue;
typedef vernode adjlist[MAXNODE];
adjlist graph;
void (*p) (int k, int *);
void inite() {
for( int i=1; i<=MAXNODE; i++) {
graph[i].vertex=i;
graph[i].firstarc=NULL;
}
}
void insert( int start, int end, int weight=0) {
arcnode * p=new arcnode;
p->vertex=end;
p->weight=weight;
p->nextarc=graph[start].firstarc;
graph[start].firstarc=p;
// 因为是无向图,所以需要添加两次!!!
arcnode *q=new arcnode;
q->vertex=start;
q->weight=weight;
q->nextarc=graph[end].firstarc;
graph[end].firstarc=q;
}
void dfs( int k, int visited[] ) {
arcnode *p;
int w;
visited[k]=1;
cout<<graph[k].vertex<<" ";
p=graph[k].firstarc;
while( p!=NULL ) {
w=p->vertex;
if( visited[w]==0 )
dfs( w, visited);
p=p->nextarc;
}
}
void bfs( int k, int visited[] ) {
int w;
arcnode *p;
visited[k]=1;
cout<<k<<" ";
gqueue.push(k);
while( !gqueue.empty() ) {
w=gqueue.front();
gqueue.pop();
p=graph[w].firstarc;
while( p!=NULL ) {
if( visited[p->vertex]==0 ) {
visited[p->vertex]=1;
cout<<p->vertex<<" ";
gqueue.push(p->vertex);
}
p=p->nextarc;
}
}
}
void travel( int n , void (*p)( int , int *)) { // 使用函数指针
int i, visited[MAXNODE];
for( i=1; i<=n; i++)
visited[i]=0;
for( i=1; i<=n; i++)
if( visited[i]==0)
(*p)( i,visited);
}
void print( int n) {
arcnode *q;
int i;
cout<<"输出无向图的邻接链表示:"<<endl;
for(i=1;i<=n;i++) {
cout<<'/t'<<i<<"/t";
cout<<graph[i].vertex<<"->";
q=graph[i].firstarc;
while(q!=NULL) {
cout<<q->vertex<<"->";
q=q->nextarc;
}
cout<<endl;
}
}
int main() {
inite();
freopen("D://in.txt", "r", stdin);
int n, e, start, end, weight;
cout<<"输入顶点的个数 "<<endl;
cin>>n;
cout<<"输入边的条数 "<<endl;
cin>>e;
for( int i=1; i<=e; i++) {
cout<<"输入第 "<<i<<" 边的起点,终点,权值";
cin>>start>>end>>weight;
cout<<endl;
insert(start,end,weight);
}
cout<<"无向图的链接表表示为: "<<endl;
print( n);
cout<<"广度搜索为: "<<endl;
travel(n, bfs );
cout<<endl;
cout<<"深度搜索为: "<<endl;
travel(n, dfs );
cout<<endl;
cin.get();
return 0;
}