从一个结点开始DFS,BFS生成树
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
#define MAX 40
#define Null 0
int visited[MAX];   //0表示未访问,1表示已经访问
ofstream out("DFS.txt");     
typedef struct CSNode
{
 int data;
 struct CSNode *firstchild,*nextsibling;
}CSNode,*CSTree;
typedef struct ArcNode

 int   adjvex;     //该弧所指向的顶点的位置
    struct ArcNode *nextarc;//指向下一条弧的指针
 }ArcNode;
typedef struct VNode
{
 int    info;     //以该点为与其相连的顶点个数
 int    citynum;  //城市编号
 string    data;   //顶点信息
 struct  ArcNode *firstarc;//指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX];
typedef struct
{
 AdjList vertices;
 int vexum,arcnum;//图的当前顶点数和弧数
 int kind;
}AlGraph;
//创建图
void CreateGraph(AlGraph &G,int num)
{  
 G.vexum=num;
 ArcNode *p;
 ifstream infile("in.txt");

 int i,j;
 for(i=0;i<num;i++)
 {
  p=G.vertices[i].firstarc=new ArcNode;
  infile>>G.vertices[i].data; //城市信息
  infile>>G.vertices[i].citynum;//城市编号
  infile>>G.vertices[i].info;    //与当前顶点相连的顶点个数
  for(j=0;j<G.vertices[i].info;j++)//输入与顶点i相连的城市编号
  {
   infile>>p->adjvex;
   p=p->nextarc=new ArcNode; 
  }
  
 }
 for(i=0;i<G.vexum;i++)
  visited[i]=0;
}
void DisplayAdj(AlGraph G)   //输出邻接表
{    
 ofstream outfile("邻接表.txt");
    int i,j;  
    ArcNode *p;
 outfile<<"图的邻接矩阵为: "<<endl;
 for(i=0;i<G.vexum;i++)
 {
  p=G.vertices[i].firstarc;
     outfile<<i+1<<"号  "<<G.vertices[i].data<<"  ";
  for(j=0;j<G.vertices[i].info;j++)
  {
   outfile<<p->adjvex<<" ";
       p=p->nextarc;
  }
     outfile<<endl;
 }
 outfile.close();
 
}  

void DFS( AlGraph G, int v )  
{  
    ArcNode *p;  

    visited[v-1] = 1;  
    p=G.vertices[v-1].firstarc;  
     for(int i=0;i<G.vertices[v-1].info;i++)
  {
   if (visited[p->adjvex-1]== 0)  
        {  
           cout<<"<"<<v<<","<<p->adjvex<<">";
    out<<"<"<<v<<","<<p->adjvex<<">";
            DFS(G,p->adjvex);  
        }  
        p = p->nextarc;  
     }


void BFS( AlGraph G, int v)  
{  
 ofstream outfile("BFS.txt");
    ArcNode *p;  
    int level[MAX], front=0, rear=0;    
    int w, i;  
    for( i = 0; i <G.vexum; i++)  
        visited[i]=0;  
    visited[v-1]=1;  
    rear++ ;  
    level[rear-1] =v;  
    while (front!=rear)  
    {  
        front++;  
        w = level[front-1];  
        p = G.vertices[w-1].firstarc;  
        for(int j=0;j<G.vertices[w-1].info;j++)
        {  
            if ( visited[p->adjvex-1] == 0 )  
            {  
               cout<<"<"<<w<<","<<p->adjvex<<">"; 
      outfile<<"<"<<w<<","<<p->adjvex<<">";
                visited[p->adjvex-1]=1;  
                rear++;  
                level[rear-1] =p->adjvex; 
            }  
            p = p->nextarc;  
        }  
    }  
    printf( "\n" );  
}  

int main()
{
 AlGraph G;
 CSTree T;
 int n,t;
 CreateGraph(G,25);
    DisplayAdj(G);
 cout<<"input begin num: "<<endl;
 cin>>n;
 t=n;
 cout<<"深度优先生成树:"<<endl;
 DFS(G,n);
 cout<<endl;
 cout<<"广度优先生成树:"<<endl;
 BFS(G,t);
 return 0;
}

 

posted on 2009-07-22 10:56  Forgetting  阅读(163)  评论(0编辑  收藏  举报