Ⅰ 求大神帮写一个c语言图的深度优先遍历,和广度优先遍历
/*深度优先*/
#include<stdio.h>
#include<stdlib.h>
struct node/*图的顶点结构*/
{
int vertex;
int flag;
struct node *nextnode;
};
typedef struct node *graph;
struct node vertex_node[10];
void creat_graph(int *node,int n)
{
graph newnode,p;/*定义一个新结点及指针*/
int start,end,i;
for(i=0;i<n;i++)
{
start=node[i*2];/*边的起点*/
end=node[i*2+1];/*边的终点*/
newnode=(graph)malloc(sizeof(struct node));
newnode->vertex=end;/*新结点的内容为边终点处顶点的内容*/
newnode->nextnode=NULL;
p=&(vertex_node[start]);/*设置指针位置*/
while(p->nextnode!=NULL)
p=p->nextnode;/*寻找链尾*/
p->nextnode=newnode;/*在链尾处插入新结点*/
}
}
void dfs(int k)
{
graph p;
vertex_node[k].flag=1;/*将标志位置1,证明该结点已访问过*/
printf("vertex[%d]",k);
p=vertex_node[k].nextnode;/*指针指向下个结点*/
while(p!=NULL)
{
if(vertex_node[p->vertex].flag==0)/*判断该结点的标志位是否为0*/
dfs(p->vertex);/*继续遍历下个结点*/
p=p->nextnode;/*若已遍历过p指向下一个结点*/
}
}
main()
{
graph p;
int node[100],i,sn,vn;
printf("please input the number of sides:\n");
scanf("%d",&sn);/*输入无向图的边数*/
printf("please input the number of vertexes\n");
scanf("%d",&vn);
printf("please input the vertexes which connected by the sides:\n");
for(i=0;i<4*sn;i++)
scanf("%d",&node[i]);/*输入每个边所连接的两个顶点,起始及结束位置不同,每边输两次*/
for(i=1;i<=vn;i++)
{
vertex_node[i].vertex=i;/*将每个顶点的信息存入数组中*/
vertex_node[i].nextnode=NULL;
}
creat_graph(node,2*sn);/*调用函数创建邻接表*/
printf("the result is:\n");
for(i=1;i<=vn;i++)/*将邻接表内容输出*/
{
printf("vertex%d:",vertex_node[i].vertex);/*输出顶点内容*/
p=vertex_node[i].nextnode;
while(p!=NULL)
{
printf("->%3d",p->vertex);/*输出邻接顶点的内容*/
p=p->nextnode;/*指针指向下个邻接顶点*/
}
printf("\n");
}
printf("the result of depth-first search is:\n");
dfs(1);/*调用函数进行深度优先遍历*/
printf("\n");
}
/***************************广度优先*******************************/
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int vertex;
    struct node *nextnode;
};
typedef struct node *graph;
struct node vertex_node[10];
#define MAXQUEUE 100
int queue[MAXQUEUE];
int front =  - 1;
int rear =  - 1;
int visited[10];
void creat_graph(int *node, int n)
{
    graph newnode, p; /*定义一个新结点及指针*/
    int start, end, i;
    for (i = 0; i < n; i++)
    {
        start = node[i *2]; /*边的起点*/
        end = node[i *2+1]; /*边的终点*/
        newnode = (graph)malloc(sizeof(struct node));
        newnode->vertex = end; /*新结点的内容为边终点处顶点的内容*/
        newnode->nextnode = NULL;
        p = &(vertex_node[start]); /*设置指针位置*/
        while (p->nextnode != NULL)
            p = p->nextnode;
        /*寻找链尾*/
        p->nextnode = newnode; /*在链尾处插入新结点*/
    }
}
int enqueue(int value) /*元素入队列*/
{
    if (rear >= MAXQUEUE)
        return  - 1;
    rear++; /*移动队尾指针*/
    queue[rear] = value;
}
int dequeue() /*元素出队列*/
{
    if (front == rear)
        return  - 1;
    front++; /*移动队头指针*/
    return queue[front];
}
void bfs(int k) /*广度优先搜索*/
{
    graph p;
    enqueue(k); /*元素入队*/
    visited[k] = 1;
    printf("vertex[%d]", k);
    while (front != rear)
     /*判断是否对空*/
    {
        k = dequeue(); /*元素出队*/
        p = vertex_node[k].nextnode;
        while (p != NULL)
        {
            if (visited[p->vertex] == 0)
             /*判断其是否被访问过*/
            {
                enqueue(p->vertex);
                visited[p->vertex] = 1; /*访问过的元素置1*/
                printf("vertex[%d]", p->vertex);
            }
            p = p->nextnode; /*访问下一个元素*/
        }
    }
}
main()
{
    graph p;
    int node[100], i, sn, vn;
    printf("please input the number of sides:\n");
    scanf("%d", &sn); /*输入无向图的边数*/
    printf("please input the number of vertexes\n");
    scanf("%d", &vn);
    printf("please input the vertexes which connected by the sides:\n");
    for (i = 0; i < 4 *sn; i++)
        scanf("%d", &node[i]);
    /*输入每个边所连接的两个顶点,起始及结束位置不同,每边输两次*/
    for (i = 1; i <= vn; i++)
    {
        vertex_node[i].vertex = i; /*将每个顶点的信息存入数组中*/
        vertex_node[i].nextnode = NULL;
    }
    creat_graph(node, 2 *sn); /*调用函数创建邻接表*/
    printf("the result is:\n");
    for (i = 1; i <= vn; i++)
    /*将邻接表内容输出*/
    {
        printf("vertex%d:", vertex_node[i].vertex); /*输出顶点内容*/
        p = vertex_node[i].nextnode;
        while (p != NULL)
        {
            printf("->%3d", p->vertex); /*输出邻接顶点的内容*/
            p = p->nextnode; /*指针指向下个邻接顶点*/
        }
        printf("\n");
    }
    printf("the result of breadth-first search is:\n");
    bfs(1); /*调用函数进行深度优先遍历*/
    printf("\n");
}
Ⅱ C语言编程 图的创建与遍历
在C语言编程中,图的创建和遍历:
#include<stdio.h>
#define N 20
#define TRUE 1
#define FALSE 0
int visited[N];
typedef struct /*队列的定义*/
{
int data[N];
int front,rear;
}queue;
typedef struct /*图的邻接矩阵*/
{
int vexnum,arcnum;
char vexs[N];
int arcs[N][N];
}
graph;
void createGraph(graph *g); /*建立一个无向图的邻接矩阵*/
void dfs(int i,graph *g); /*从第i个顶点出发深度优先搜索*/
void tdfs(graph *g); /*深度优先搜索整个图*/
void bfs(int k,graph *g); /*从第k个顶点广度优先搜索*/
void tbfs(graph *g); /*广度优先搜索整个图*/
void init_visit(); /*初始化访问标识数组*/
void createGraph(graph *g) /*建立一个无向图的邻接矩阵*/
{ int i,j;
char v;
g->vexnum=0;
g->arcnum=0;
i=0;
printf("输入顶点序列(以#结束):
");
while((v=getchar())!='#')
{
g->vexs[i]=v; /*读入顶点信息*/
i++;
}
g->vexnum=i; /*顶点数目*/
for(i=0;i<g->vexnum;i++) /*邻接矩阵初始化*/
for(j=0;j<g->vexnum;j++)
g->arcs[i][j]=0;
printf("输入边的信息:
");
scanf("%d,%d",&i,&j); /*读入边i,j*/
while(i!=-1) /*读入i,j为-1时结束*/
{
g->arcs[i][j]=1;
g->arcs[j][i]=1;
scanf("%d,%d",&i,&j);
}
}
void dfs(int i,graph *g) /*从第i个顶点出发深度优先搜索*/
{
int j;
printf("%c",g->vexs[i]);
visited[i]=TRUE;
for(j=0;j<g->vexnum;j++)
if((g->arcs[i][j]==1)&&(!visited[j]))
dfs(j,g);
}
void tdfs(graph *g) /*深度优先搜索整个图*/
{
int i;
printf("
从顶点%C开始深度优先搜索序列:",g->vexs[0]);
for(i=0;i<g->vexnum;i++)
if(visited[i]!=TRUE)
dfs(i,g);
}
void bfs(int k,graph *g) /*从第k个顶点广度优先搜索*/
{
int i,j;
queue qlist,*q;
q=&qlist;
q->rear=0;
q->front=0;
printf("%c",g->vexs[k]);
visited[k]=TRUE;
q->data[q->rear]=k;
q->rear=(q->rear+1)%N;
while(q->rear!=q->front)
{
i=q->data[q->front];
q->front=(q->front+1)%N;
for(j=0;j<g->vexnum;j++)
if((g->arcs[i][j]==1)&&(!visited[j]))
{
printf("%c",g->vexs[j]);
visited[j]=TRUE;
q->data[q->rear]=j;
q->rear=(q->rear+1)%N;
}
}
}
void tbfs(graph *g) /*广度优先搜索整个图*/
{
int i;
printf("
从顶点%C开始广度优先搜索序列:",g->vexs[0]);
for(i=0;i<g->vexnum;i++)
if(visited[i]!=TRUE)
bfs(i,g);
printf("
");
}
void init_visit() /*初始化访问标识数组*/
{
int i;
for(i=0;i<N;i++)
visited[i]=FALSE;
}
int main()
{
graph ga;
int i,j;
createGraph(&ga);
printf("无向图的邻接矩阵:
");
for(i=0;i<ga.vexnum;i++)
{
for(j=0;j<ga.vexnum;j++)
printf("%3d",ga.arcs[i][j]);
printf("
");
}
init_visit();
tdfs(&ga);
init_visit();
tbfs(&ga);
return 0;
}
Ⅲ 求c语言图的深度优先遍历算法
#define MaxVerNum 100      /* 最大顶点数为*/
typedef enum {False,True} boolean;
#include "stdio.h"
#include "stdlib.h"
boolean visited[MaxVerNum];
typedef  struct node /* 表结点*/
{
	int adjvex;/* 邻接点域,一般是放顶点对应的序号或在表头向量中的下标*/
	char  Info;         /*与边(或弧)相关的信息*/
	struct node  * next;   /* 指向下一个邻接点的指针域*/
} EdgeNode;       
typedef  struct vnode /* 顶点结点*/
{ 
	char  vertex; /* 顶点域*/
	EdgeNode  * firstedge;      /* 边表头指针*/
} VertexNode;      
typedef  struct
{ 
	VertexNode  adjlist[MaxVerNum];    /* 邻接表*/
	int n,e;                 /* 顶点数和边数*/
} ALGraph; /* ALGraph是以邻接表方式存储的图类型*/
//建立一个无向图的邻接表存储的算法如下:
void CreateALGraph(ALGraph *G)/* 建立有向图的邻接表存储*/
{
	int i,j,k;
	int N,E;
	EdgeNode *p;
	printf("请输入顶点数和边数:");
	scanf("%d %d",&G->n,&G->e);  
	printf("n=%d,e=%d\n\n",G->n,G->e);
	getchar();
	for(i=0;i<G->n;i++)   /* 建立有n个顶点的顶点表*/
	{
		printf("请输入第%d个顶点字符信息(共%d个):",i+1,G->n);
		scanf("%c",&(G->adjlist[i].vertex));   /* 读入顶点信息*/
		getchar();
		G->adjlist[i].firstedge=NULL;    /* 顶点的边表头指针设为空*/
	}
	for(k=0;k<2*G->e;k++)              /* 建立边表*/
	{
		printf("请输入边<Vi,Vj>对应的顶点序号(共%d个):",2*G->e);
		scanf("%d %d",&i,&j);/* 读入边<Vi,Vj>的顶点对应序号*/
		p=(EdgeNode *)malloc(sizeof(EdgeNode)); // 生成新边表结点p 
		p->adjvex=j;  /* 邻接点序号为j */
		p->next=G->adjlist[i].firstedge;/* 将结点p插入到顶点Vi的链表头部*/
		G->adjlist[i].firstedge=p;
	} 
	printf("\n图已成功创建!对应的邻接表如下:\n");
	for(i=0;i<G->n;i++)
	{
		p=G->adjlist[i].firstedge;
		printf("%c->",G->adjlist[i].vertex);
		while(p!=NULL)
		{
			printf("[ %c ]",G->adjlist[p->adjvex].vertex);
			p=p->next;
		}
		printf("\n");
	}
	printf("\n");
}  /*CreateALGraph*/
int FirstAdjVertex(ALGraph *g,int v)//找图g中与顶点v相邻的第一个顶点
{
    if(g->adjlist[v].firstedge!=NULL) return (g->adjlist[v].firstedge)->adjvex;
	else return 0;
}
int NextAdjVertex(ALGraph  *g ,int vi,int vj )//找图g中与vi相邻的,相对相邻顶点vj的下一个相邻顶点
{
	EdgeNode *p;
	p=g->adjlist[vi].firstedge;
	while( p!=NULL && p->adjvex!=vj) p=p->next;
	if(p!=NULL && p->next!=NULL)  return p->next->adjvex;
	else return 0;
}
void  DFS(ALGraph *G,int v) /* 从第v个顶点出发深度优先遍历图G */
{ 
	int w;
    printf("%c ",G->adjlist[v].vertex);
	visited[v]=True;   /* 访问第v个顶点,并把访问标志置True */
	for(w=FirstAdjVertex(G,v);w;w=NextAdjVertex(G,v,w))
		if (!visited[w]) DFS(G,w);			/* 对v尚未访问的邻接顶点w递归调用DFS */
}
void DFStraverse(ALGraph  *G)
/*深度优先遍历以邻接表表示的图G,而以邻接矩阵表示时,算法完全相同*/
{   int i,v;
    for(v=0;v<G->n;v++)
           visited[v]=False;/*标志向量初始化*/
    //for(i=0;i<G->n;i++)
            if(!visited[0]) DFS(G,0);
}/*DFS*/
void main()
{
	ALGraph G;
	CreateALGraph(&G);
	printf("该无向图的深度优先搜索序列为:");
 	DFStraverse(&G);
	printf("\nSuccess!\n");
}
Ⅳ 图的遍历(c语言)完整上机代码
//图的遍历算法程序 
 
//图的遍历是指按某条搜索路径访问图中每个结点,使得每个结点均被访问一次,而且仅被访问一次。图的遍历有深度遍历算法和广度遍历算法,程序如下:  
#include <iostream>
//#include <malloc.h>
#define INFINITY 32767
#define MAX_VEX 20 //最大顶点个数
#define QUEUE_SIZE (MAX_VEX+1) //队列长度
using namespace std;
bool *visited;  //访问标志数组
//图的邻接矩阵存储结构
typedef struct{
  char *vexs; //顶点向量
  int arcs[MAX_VEX][MAX_VEX]; //邻接矩阵
  int vexnum,arcnum; //图的当前顶点数和弧数
}Graph;
//队列类
class Queue{
  public:
  void InitQueue(){
    base=(int *)malloc(QUEUE_SIZE*sizeof(int));
    front=rear=0;
  }
  void EnQueue(int e){
    base[rear]=e;
    rear=(rear+1)%QUEUE_SIZE;
  }
  void DeQueue(int &e){
    e=base[front];
    front=(front+1)%QUEUE_SIZE;
  }
  public:
  int *base;
  int front;
  int rear;
};
//图G中查找元素c的位置
int Locate(Graph G,char c){
  for(int i=0;i<G.vexnum;i++)
  if(G.vexs[i]==c) return i;
  return -1;
}
//创建无向网
void CreateUDN(Graph &G){
  int i,j,w,s1,s2;
  char a,b,temp;
  printf("输入顶点数和弧数:");
  scanf("%d%d",&G.vexnum,&G.arcnum);
  temp=getchar(); //接收回车
  G.vexs=(char *)malloc(G.vexnum*sizeof(char)); //分配顶点数目
  printf("输入%d个顶点.\n",G.vexnum);
  for(i=0;i<G.vexnum;i++){ //初始化顶点
    printf("输入顶点%d:",i);
    scanf("%c",&G.vexs[i]);
    temp=getchar(); //接收回车 
  }
  for(i=0;i<G.vexnum;i++) //初始化邻接矩阵
    for(j=0;j<G.vexnum;j++)
      G.arcs[i][j]=INFINITY;
  printf("输入%d条弧.\n",G.arcnum);
  for(i=0;i<G.arcnum;i++){ //初始化弧
    printf("输入弧%d:",i);
    scanf("%c %c %d",&a,&b,&w); //输入一条边依附的顶点和权值
    temp=getchar(); //接收回车
    s1=Locate(G,a);
    s2=Locate(G,b);
    G.arcs[s1][s2]=G.arcs[s2][s1]=w;
  }
}
//图G中顶点k的第一个邻接顶点
int FirstVex(Graph G,int k){
  if(k>=0 && k<G.vexnum){ //k合理
    for(int i=0;i<G.vexnum;i++)
      if(G.arcs[k][i]!=INFINITY) return i;
  }
  return -1;
}
//图G中顶点i的第j个邻接顶点的下一个邻接顶点
int NextVex(Graph G,int i,int j){
  if(i>=0 && i<G.vexnum && j>=0 && j<G.vexnum){ //i,j合理
    for(int k=j+1;k<G.vexnum;k++)
      if(G.arcs[i][k]!=INFINITY) return k;
  }
  return -1;
}
//深度优先遍历
void DFS(Graph G,int k){
  int i;
  if(k==-1){ //第一次执行DFS时,k为-1
    for(i=0;i<G.vexnum;i++)
      if(!visited[i]) DFS(G,i); //对尚未访问的顶点调用DFS
  }
  else{ 
    visited[k]=true;
    printf("%c ",G.vexs[k]); //访问第k个顶点
    for(i=FirstVex(G,k);i>=0;i=NextVex(G,k,i))
      if(!visited[i]) DFS(G,i); //对k的尚未访问的邻接顶点i递归调用DFS
  }
}
//广度优先遍历
void BFS(Graph G){
  int k;
  Queue Q; //辅助队列Q
  Q.InitQueue();
  for(int i=0;i<G.vexnum;i++)
    if(!visited[i]){ //i尚未访问
      visited[i]=true;
      printf("%c ",G.vexs[i]);
      Q.EnQueue(i); //i入列
      while(Q.front!=Q.rear){
        Q.DeQueue(k); //队头元素出列并置为k
        for(int w=FirstVex(G,k);w>=0;w=NextVex(G,k,w))
          if(!visited[w]){ //w为k的尚未访问的邻接顶点
            visited[w]=true;
            printf("%c ",G.vexs[w]);
            Q.EnQueue(w);
          }
      }
    }
}
//主函数
void main(){
  int i;
  Graph G;
  CreateUDN(G);
  visited=(bool *)malloc(G.vexnum*sizeof(bool)); 
  printf("\n广度优先遍历: ");
  for(i=0;i<G.vexnum;i++)
  visited[i]=false;
  DFS(G,-1);
  printf("\n深度优先遍历: ");
  for(i=0;i<G.vexnum;i++)
  visited[i]=false;
  BFS(G);
  printf("\n程序结束.\n");
}
输出结果为(红色为键盘输入的数据,权值都置为1):
输入顶点数和弧数:8 9
输入8个顶点.
输入顶点0:a
输入顶点1:b
输入顶点2:c
输入顶点3:d
输入顶点4:e
输入顶点5:f
输入顶点6:g
输入顶点7:h
输入9条弧.
输入弧0:a b 1
输入弧1:b d 1
输入弧2:b e 1
输入弧3:d h 1
输入弧4:e h 1
输入弧5:a c 1
输入弧6:c f 1
输入弧7:c g 1
输入弧8:f g 1
广度优先遍历: a b d h e c f g 
深度优先遍历: a b c d e f g h 
程序结束.
已经在vc++内运行通过,这个程序已经达到要求了呀~
Ⅳ 用C语言实现 图的邻接表和邻接矩阵数据结构的定义、创建;图的深度优先遍历、广度优先遍历。
/*
程序1:邻接表的dfs,bfs
其中n是点的个数,m是边的个数,你需要输入m条有向边,如果要无向只需要反过来多加一遍即可。
*/
#include<stdio.h>
#include<string.h>
#defineMAXM100000
#defineMAXN10000
intnext[MAXM],first[MAXN],en[MAXM],n,m,flag[MAXN],pd,dl[MAXN],head,tail;
voidinput_data()
{
scanf("%d%d",&n,&m);
inti,x,y;
for(i=1;i<=m;i++)
{
intx,y;
scanf("%d%d",&x,&y);
next[i]=first[x];
first[x]=i;
en[i]=y;
}
}
voidpre()
{
memset(flag,0,sizeof(flag));
pd=0;
}
voiddfs(intx)
{
flag[x]=1;
if(!pd)
{
pd=1;
printf("%d",x);
}else
printf("%d",x);
intp=first[x];
while(p!=0)
{
inty=en[p];
if(!flag[y])dfs(y);
p=next[p];
}
}
voidbfs(intk)
{
head=0;tail=1;
flag[k]=1;dl[1]=k;
while(head<tail)
{
intx=dl[++head];
if(!pd)
{
pd=1;
printf("%d",x);
}elseprintf("%d",x);
intp=first[x];
while(p!=0)
{
inty=en[p];
if(!flag[y])
{
flag[y]=1;
dl[++tail]=y;
}
p=next[p];
}
}
}
intmain()
{
input_data();//读入图信息。
pre();//初始化
printf("图的深度优先遍历结果:");
inti;
for(i=1;i<=n;i++)//对整张图进行dfs;加这个for主要是为了防止不多个子图的情况
if(!flag[i])
dfs(i);
printf(" ------------------------------------------------------------- ");
pre();//初始化
printf("图的广度优先遍历结果为:");
for(i=1;i<=n;i++)
if(!flag[i])
bfs(i);
printf(" ----------------------end------------------------------------ ");
return0;
}
/*
程序2:邻接矩阵
图的广度优先遍历和深度优先遍历
*/
#include<stdio.h>
#include<string.h>
#defineMAXN1000
intn,m,w[MAXN][MAXN],flag[MAXN],pd,dl[MAXN];
voidinput_data()
{
scanf("%d%d",&n,&m);
inti;
for(i=1;i<=m;i++)
{
intx,y;
scanf("%d%d",&x,&y);
w[x][0]++;
w[x][w[x][0]]=y;
}
}
voidpre()
{
memset(flag,0,sizeof(flag));
pd=0;
}
voiddfs(intx)
{
flag[x]=1;
if(!pd)
{
pd=1;
printf("%d",x);
}elseprintf("%d",x);
inti;
for(i=1;i<=w[x][0];i++)
{
inty=w[x][i];
if(!flag[y])dfs(y);
}
}
voidbfs(intt)
{
inthead=0,tail=1;
dl[1]=t;flag[t]=1;
while(head<tail)
{
intx=dl[++head];
if(!pd)
{
pd=1;
printf("%d",x);
}elseprintf("%d",x);
inti;
for(i=1;i<=w[x][0];i++)
{
inty=w[x][i];
if(!flag[y])
{
flag[y]=1;
dl[++tail]=y;
}
}
}
}
intmain()
{
input_data();
printf("图的深度优先遍历结果:");
pre();
inti;
for(i=1;i<=n;i++)
if(!flag[i])
dfs(i);
printf(" --------------------------------------------------------------- ");
printf("图的广度优先遍历结果:");
pre();
for(i=1;i<=n;i++)
if(!flag[i])
bfs(i);
printf(" -----------------------------end-------------------------------- ");
return0;
}
Ⅵ C语言编写程序实现图的遍历操作
楼主你好,下面是源程序!
 
/*/////////////////////////////////////////////////////////////*/
/*                           图的深度优先遍历                  */
/*/////////////////////////////////////////////////////////////*/
#include <stdlib.h>
#include <stdio.h>
struct node                       /* 图顶点结构定义     */
{
   int vertex;                    /* 顶点数据信息       */
   struct node *nextnode;         /* 指下一顶点的指标   */
};
typedef struct node *graph;       /* 图形的结构新型态   */
struct node head[9];              /* 图形顶点数组       */
int visited[9];                   /* 遍历标记数组       */
 
/********************根据已有的信息建立邻接表********************/
void creategraph(int node[20][2],int num)/*num指的是图的边数*/
{
   graph newnode;                 /*指向新节点的指针定义*/
   graph ptr;
   int from;                      /* 边的起点          */
   int to;                        /* 边的终点          */
   int i;
   for ( i = 0; i < num; i++ )    /* 读取边线信息,插入邻接表*/
   {
      from = node[i][0];         /*    边线的起点            */
      to = node[i][1];           /*   边线的终点             */
      
   /* 建立新顶点 */
      newnode = ( graph ) malloc(sizeof(struct node));
      newnode->vertex = to;        /* 建立顶点内容       */
      newnode->nextnode = NULL;    /* 设定指标初值       */
      ptr = &(head[from]);         /* 顶点位置           */
      while ( ptr->nextnode != NULL ) /* 遍历至链表尾   */
         ptr = ptr->nextnode;     /* 下一个顶点         */
      ptr->nextnode = newnode;    /* 插入节点        */
   }
}
/**********************  图的深度优先搜寻法********************/
void dfs(int current)
{
   graph ptr;
   visited[current] = 1;          /* 记录已遍历过       */
   printf("vertex[%d]\n",current);   /* 输出遍历顶点值     */
   ptr = head[current].nextnode;  /* 顶点位置           */
   while ( ptr != NULL )          /* 遍历至链表尾       */
   {
      if ( visited[ptr->vertex] == 0 )  /* 如过没遍历过 */
         dfs(ptr->vertex);              /* 递回遍历呼叫 */
      ptr = ptr->nextnode;              /* 下一个顶点   */
   }
}
/****************************** 主程序******************************/
void main()
{
   graph ptr;
   int node[20][2] = { {1, 2}, {2, 1},  /* 边线数组     */
                       {1, 3}, {3, 1},
                       {1, 4}, {4, 1},
                       {2, 5}, {5, 2},
                       {2, 6}, {6, 2},
                       {3, 7}, {7, 3},
                       {4, 7}, {4, 4},
                       {5, 8}, {8, 5},
                       {6, 7}, {7, 6},
                       {7, 8}, {8, 7} };
   int i;
   clrscr();
   for ( i = 1; i <= 8; i++ )      /*   顶点数组初始化  */
   {
      head[i].vertex = i;         /*    设定顶点值      */
      head[i].nextnode = NULL;    /*       指针为空     */
      visited[i] = 0;             /* 设定遍历初始标志   */
   }
   creategraph(node,20);          /*    建立邻接表      */
   printf("Content of the gragh's ADlist is:\n");
   for ( i = 1; i <= 8; i++ )
   {
      printf("vertex%d ->",head[i].vertex); /* 顶点值    */
      ptr = head[i].nextnode;             /* 顶点位置   */
      while ( ptr != NULL )       /* 遍历至链表尾       */
      {
         printf(" %d ",ptr->vertex);  /* 印出顶点内容   */
         ptr = ptr->nextnode;         /* 下一个顶点     */
      }
      printf("\n");               /*   换行             */
   }
   printf("\nThe end of the dfs are:\n");
   dfs(1);                        /* 打印输出遍历过程   */
   printf("\n");                  /* 换行               */
   puts(" Press any key to quit...");
   getch();
}
/*//////////////////////////////////////////*/
/*    图形的广度优先搜寻法                 */
/* ///////////////////////////////////////*/
#include <stdlib.h>
#include <stdio.h>
#define MAXQUEUE 10               /* 队列的最大容量       */
struct node                       /* 图的顶点结构定义     */
{
   int vertex;
   struct node *nextnode;
};
typedef struct node *graph;       /*  图的结构指针        */
struct node head[9];              /* 图的顶点数组         */
int visited[9];                   /* 遍历标记数组         */
int queue[MAXQUEUE];              /* 定义序列数组         */
int front = -1;                   /* 序列前端            */
int rear = -1;                    /* 序列后端            */
/***********************二维数组向邻接表的转化****************************/
void creategraph(int node[20][2],int num)
{
   graph newnode;                 /*  顶点指针           */
   graph ptr;
   int from;                      /* 边起点             */
   int to;                        /* 边终点             */
   int i;
   for ( i = 0; i < num; i++ )    /* 第i条边的信息处理    */
   {
      from = node[i][0];           /* 边的起点           */
      to = node[i][1];           /* 边的终点             */
   /*              建立新顶点                         */
      newnode = ( graph ) malloc(sizeof(struct node));
      newnode->vertex = to;       /*    顶点内容         */
      newnode->nextnode = NULL;   /* 设定指针初值         */
      ptr = &(head[from]);        /* 顶点位置             */
      while ( ptr->nextnode != NULL ) /* 遍历至链表尾     */
         ptr = ptr->nextnode;         /* 下一个顶点       */
      ptr->nextnode = newnode;        /* 插入第i个节点的链表尾部 */
   }
}
/************************ 数值入队列************************************/
int enqueue(int value)
{
   if ( rear >= MAXQUEUE )        /* 检查伫列是否全满     */
      return -1;                  /* 无法存入             */
   rear++;                        /* 后端指标往前移       */
   queue[rear] = value;           /* 存入伫列             */
}
/************************* 数值出队列*********************************/
int dequeue()
{
   if ( front  == rear )          /* 队列是否为空         */
      return -1;                  /* 为空,无法取出       */
   front++;                       /* 前端指标往前移       */
   return queue[front];           /* 从队列中取出信息     */
}
/***********************  图形的广度优先遍历************************/
void bfs(int current)
{
   graph ptr;
   /* 处理第一个顶点 */
   enqueue(current);              /* 将顶点存入队列       */
   visited[current] = 1;          /* 已遍历过记录标志置疑1*/
   printf(" Vertex[%d]\n",current);   /* 打印输出遍历顶点值 */
   while ( front != rear )        /* 队列是否为空         */
   {
      current = dequeue();        /* 将顶点从队列列取出   */
      ptr = head[current].nextnode;   /* 顶点位置         */
      while ( ptr != NULL )           /* 遍历至链表尾     */
      {
         if ( visited[ptr->vertex] == 0 ) /*顶点没有遍历过*/
         {
            enqueue(ptr->vertex);     /* 奖定点放入队列   */
            visited[ptr->vertex] = 1; /* 置遍历标记为1    */
     printf(" Vertex[%d]\n",ptr->vertex);/* 印出遍历顶点值 */
         }
         ptr = ptr->nextnode;     /* 下一个顶点           */
      }
   }
}
/***********************  主程序  ************************************/
/*********************************************************************/
void main()
{
   graph ptr;
   int node[20][2] = { {1, 2}, {2, 1},  /* 边信息数组       */
                       {6, 3}, {3, 6},
                       {2, 4}, {4, 2},
                       {1, 5}, {5, 1},
                       {3, 7}, {7, 3},
                       {1, 7}, {7, 1},
                       {4, 8}, {8, 4},
                       {5, 8}, {8, 5},
                       {2, 8}, {8, 2},
                       {7, 8}, {8, 7} };
   int i;
   clrscr();
   puts("This is an example of Width Preferred Traverse of Gragh.\n");
   for ( i = 1; i <= 8; i++ )        /*顶点结构数组初始化*/
   {
      head[i].vertex = i;
      head[i].nextnode = NULL;
      visited[i] = 0;
   }
   creategraph(node,20);       /* 图信息转换,邻接表的建立 */
   printf("The content of the graph's allist is:\n");
   for ( i = 1; i <= 8; i++ )
   {
      printf(" vertex%d =>",head[i].vertex); /* 顶点值       */
      ptr = head[i].nextnode;             /* 顶点位置     */
      while ( ptr != NULL )       /* 遍历至链表尾         */
      {
         printf(" %d ",ptr->vertex);  /* 打印输出顶点内容     */
         ptr = ptr->nextnode;         /* 下一个顶点       */
      }
      printf("\n");               /* 换行                 */
   }
   printf("The contents of BFS are:\n");
   bfs(1);                        /* 打印输出遍历过程         */
   printf("\n");                  /* 换行                 */
   puts(" Press any key to quit...");
   getch();
}
Ⅶ 用c语言编一段图的创建与遍历的代码
//#include <stdafx.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 20
typedef char VertexType;//顶点数据类型
bool visited[MAX_SIZE];
typedef struct ArcNode{
int AdjVex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
VertexType data;
ArcNode *firstarc;
}VNode,AdjList[MAX_SIZE];
typedef struct{
int vexnum,arcnum;
AdjList Vertices;
}ALGraph;
int LocateVex(ALGraph G,char v)
{
int i;
for(i=0;i<G.vexnum;i++)
{
if(G.Vertices[i].data==v) return i;
}
return -1;
}
void CreatG(ALGraph &G)
{
int i,a,b;
char m,n;
ArcNode *p,*q;
scanf("%d %d",&G.vexnum,&G.arcnum);
printf("请依次输入顶点:\n");
for(i=0;i<G.vexnum;i++)
{
flushall();
scanf("%c",&G.Vertices[i].data);
G.Vertices[i].firstarc=NULL;
}
printf("请依次输入边:\n");
for(i=0;i<G.arcnum;i++)
{
flushall();
scanf("%c %c",&m,&n);
a=LocateVex(G,m);
b=LocateVex(G,n);
p=(ArcNode *)malloc(sizeof(ArcNode));
p->AdjVex=b;
p->nextarc=G.Vertices[a].firstarc;
G.Vertices[a].firstarc=p;
q=(ArcNode *)malloc(sizeof(ArcNode));
q->AdjVex=a;
q->nextarc=G.Vertices[b].firstarc;
G.Vertices[b].firstarc=q;
}
}
int FirstAdjVex(ALGraph G,int v)
{
ArcNode *p;
p=G.Vertices[v].firstarc;
return p->AdjVex;
}
int NextAdjVex(ALGraph G,int v,int w)
{
ArcNode *p;
p=G.Vertices[v].firstarc;
while(p->nextarc)
{
return p->nextarc->AdjVex;
}
}
void DFS(ALGraph G,int v)
{
int w;
visited[v]=true;
printf("%c ",G.Vertices[v].data);
for(w=FirstAdjVex(G,v);w>=0;w=NextAdjVex(G,v,w))
if(!visited[w])
DFS(G,w);
}
void DFSTraverse(ALGraph G){
int v;
for(v=0;v<G.vexnum;v++)
visited[v]=false;
for(v=0;v<G.vexnum;v++)
if(!visited[v])
DFS(G,v);
}
void main()
{
ALGraph G;
printf("请输入图的顶点数和边数:\n");
CreatG(G);
printf("深度优先遍历结果:\n");
DFSTraverse(G);
} 
希望对你有用
Ⅷ 数据结构(C语言版) 图的遍历和拓扑排序
#include<string.h>
#include<ctype.h>
#include<malloc.h> /* malloc()等*/
#include<limits.h> /* INT_MAX 等*/
#include<stdio.h> /* EOF(=^Z 或F6),NULL */
#include<stdlib.h> /* atoi() */
#include<io.h> /* eof() */
#include<math.h> /* floor(),ceil(),abs() */
#include<process.h> /* exit() */
/* 函数结果状态代码*/
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
/* #define OVERFLOW -2 因为在math.h 中已定义OVERFLOW 的值为3,故去掉此行*/
typedef int Status; /* Status 是函数的类型,其值是函数结果状态代码,如OK 等*/
typedef int Boolean; Boolean 是布尔类型,其值是TRUE 或FALSE */
/* .........................*/
#define MAX_VERTEX_NUM 20
typedef enum{DG,DN,AG,AN}GraphKind; /* {有向图,有向网,无向图,无向网} */
typedef struct ArcNode
{
int adjvex; /* 该弧所指向的顶点的位置*/
struct ArcNode *nextarc; /* 指向下一条弧的指针*/
InfoType *info; /* 网的权值指针) */
}ArcNode; /* 表结点*/
typedef struct
{
VertexType data; /* 顶点信息*/
ArcNode *firstarc; /* 第一个表结点的地址,指向第一条依附该顶点的弧的指针*/
}VNode,AdjList[MAX_VERTEX_NUM]; /* 头结点*/
typedef struct
{
AdjList vertices;
int vexnum,arcnum; /* 图的当前顶点数和弧数*/
int kind; /* 图的种类标志*/
}ALGraph;
/* .........................*/
/* .........................*/
/*ALGraphAlgo.cpp 图的邻接表存储(存储结构由ALGraphDef.h 定义)的基本操作*/
int LocateVex(ALGraph G,VertexType u)
{ /* 初始条件: 图G 存在,u 和G 中顶点有相同特征*/
/* 操作结果: 若G 中存在顶点u,则返回该顶点在图中位置;否则返回-1 */
int i;
for(i=0;i<G.vexnum;++i)
if(strcmp(u,G.vertices[i].data)==0)
return i;
return -1;
}
Status CreateGraph(ALGraph &G)
{ /* 采用邻接表存储结构,构造没有相关信息的图G(用一个函数构造4 种图) */
int i,j,k;
int w; /* 权值*/
VertexType va,vb;
ArcNode *p;
printf("请输入图的类型(有向图:0,有向网:1,无向图:2,无向网:3): ");
scanf("%d",&(G.kind));
printf("请输入图的顶点数,边数: ");
scanf("%d,%d",&(G.vexnum),&(G.arcnum));
printf("请输入%d 个顶点的值(<%d 个字符):\n",G.vexnum,MAX_NAME);
for(i=0;i<G.vexnum;++i) /* 构造顶点向量*/
{
scanf("%s",G.vertices[i].data);
G.vertices[i].firstarc=NULL;
}
if(G.kind==1||G.kind==3) /* 网*/
printf("请顺序输入每条弧(边)的权值、弧尾和弧头(以空格作为间隔):\n");
else /* 图*/
printf("请顺序输入每条弧(边)的弧尾和弧头(以空格作为间隔):\n");
for(k=0;k<G.arcnum;++k) /* 构造表结点链表*/
{
if(G.kind==1||G.kind==3) /* 网*/
scanf("%d%s%s",&w,va,vb);
else /* 图*/
scanf("%s%s",va,vb);
i=LocateVex(G,va); /* 弧尾*/
j=LocateVex(G,vb); /* 弧头*/
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=j;
if(G.kind==1||G.kind==3) /* 网*/
{
p->info=(int *)malloc(sizeof(int));
*(p->info)=w;
}
else
p->info=NULL; /* 图*/
p->nextarc=G.vertices[i].firstarc; /* 插在表头*/
G.vertices[i].firstarc=p;
if(G.kind>=2) /* 无向图或网,产生第二个表结点*/
{
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=i;
if(G.kind==3) /* 无向网*/
{
p->info=(int*)malloc(sizeof(int));
*(p->info)=w;
}
else
p->info=NULL; /* 无向图*/
p->nextarc=G.vertices[j].firstarc; /* 插在表头*/
G.vertices[j].firstarc=p;
}
}
return OK;
}
void DestroyGraph(ALGraph &G)
{ /* 初始条件: 图G 存在。操作结果: 销毁图G */
int i;
ArcNode *p,*q;
G.vexnum=0;
G.arcnum=0;
for(i=0;i<G.vexnum;++i)
{
p=G.vertices[i].firstarc;
while(p)
{
q=p->nextarc;
if(G.kind%2) /* 网*/
free(p->info);
free(p);
p=q;
}
}
}
VertexType* GetVex(ALGraph G,int v)
{ /* 初始条件: 图G 存在,v 是G 中某个顶点的序号。操作结果: 返回v 的值*/
if(v>=G.vexnum||v<0)
exit(ERROR);
return &G.vertices[v].data;
}
int FirstAdjVex(ALGraph G,VertexType v)
{ /* 初始条件: 图G 存在,v 是G 中某个顶点*/
/* 操作结果: 返回v 的第一个邻接顶点的序号。若顶点在G 中没有邻接顶点,则返回-1 */
ArcNode *p;
int v1;
v1=LocateVex(G,v); /* v1 为顶点v 在图G 中的序号*/
p=G.vertices[v1].firstarc;
if(p)
return p->adjvex;
else
return -1;
}
int NextAdjVex(ALGraph G,VertexType v,VertexType w)
{ /* 初始条件: 图G 存在,v 是G 中某个顶点,w 是v 的邻接顶点*/
/* 操作结果: 返回v 的(相对于w 的)下一个邻接顶点的序号。*/
/* 若w 是v 的最后一个邻接点,则返回-1 */
ArcNode *p;
int v1,w1;
v1=LocateVex(G,v); /* v1 为顶点v 在图G 中的序号*/
w1=LocateVex(G,w); /* w1 为顶点w 在图G 中的序号*/
p=G.vertices[v1].firstarc;
while(p&&p->adjvex!=w1) /* 指针p 不空且所指表结点不是w */
p=p->nextarc;
if(!p||!p->nextarc) /* 没找到w 或w 是最后一个邻接点*/
return -1;
else /* p->adjvex==w */
return p->nextarc->adjvex; /* 返回v 的(相对于w 的)下一个邻接顶点的序号*/
}
Boolean visited[MAX_VERTEX_NUM]; /* 访问标志数组(全局量) */
void(*VisitFunc)(char* v); /* 函数变量(全局量) */
void DFS(ALGraph G,int v)
{ /* 从第v 个顶点出发递归地深度优先遍历图G。算法7.5 */
int w;
VertexType v1,w1;
strcpy(v1,*GetVex(G,v));
visited[v]=TRUE; /* 设置访问标志为TRUE(已访问) */
VisitFunc(G.vertices[v].data); /* 访问第v 个顶点*/
for(w=FirstAdjVex(G,v1);w>=0;w=NextAdjVex(G,v1,strcpy(w1,*GetVex(G,w))))
if(!visited[w])
DFS(G,w); /* 对v 的尚未访问的邻接点w 递归调用DFS */
}
void DFSTraverse(ALGraph G,void(*Visit)(char*))
{ /* 对图G 作深度优先遍历。算法7.4 */
int v;
VisitFunc=Visit; /* 使用全局变量VisitFunc,使DFS 不必设函数指针参数*/
for(v=0;v<G.vexnum;v++)
visited[v]=FALSE; /* 访问标志数组初始化*/
for(v=0;v<G.vexnum;v++)
if(!visited[v])
DFS(G,v); /* 对尚未访问的顶点调用DFS */
printf("\n");
}
typedef int QElemType; /* 队列类型*/
#include"LinkQueueDef.h"
#include"LinkQueueAlgo.h"
void BFSTraverse(ALGraph G,void(*Visit)(char*))
{/*按广度优先非递归遍历图G。使用辅助队列Q 和访问标志数组visited。算法7.6 */
int v,u,w;
VertexType u1,w1;
LinkQueue Q;
for(v=0;v<G.vexnum;++v)
visited[v]=FALSE; /* 置初值*/
InitQueue(Q); /* 置空的辅助队列Q */
for(v=0;v<G.vexnum;v++) /* 如果是连通图,只v=0 就遍历全图*/
if(!visited[v]) /* v 尚未访问*/
{
visited[v]=TRUE;
Visit(G.vertices[v].data);
EnQueue(Q,v); /* v 入队列*/
while(!QueueEmpty(Q)) /* 队列不空*/
{
DeQueue(Q,u); /* 队头元素出队并置为u */
strcpy(u1,*GetVex(G,u));
for(w=FirstAdjVex(G,u1);w>=0;w=NextAdjVex(G,u1,strcpy(w1,*GetVex(G,w))))
if(!visited[w]) /* w 为u 的尚未访问的邻接顶点*/
{
visited[w]=TRUE;
Visit(G.vertices[w].data);
EnQueue(Q,w); /* w 入队*/
}
}
}
printf("\n");
}
void Display(ALGraph G)
{ /* 输出图的邻接矩阵G */
int i;
ArcNode *p;
switch(G.kind)
{ case DG: printf("有向图\n"); break;
case DN: printf("有向网\n"); break;
case AG: printf("无向图\n"); break;
case AN: printf("无向网\n");
}
printf("%d 个顶点:\n",G.vexnum);
for(i=0;i<G.vexnum;++i)
printf("%s ",G.vertices[i].data);
printf("\n%d 条弧(边):\n",G.arcnum);
for(i=0;i<G.vexnum;i++)
{
p=G.vertices[i].firstarc;
while(p)
{
if(G.kind<=1) /* 有向*/
{
printf("%s→%s ",G.vertices[i].data,G.vertices[p->adjvex].data);
if(G.kind==DN) /* 网*/
printf(":%d ",*(p->info));
}
else /* 无向(避免输出两次) */
{
if(i<p->adjvex)
{
printf("%s-%s ",G.vertices[i].data,G.vertices[p->adjvex].data);
if(G.kind==AN) /* 网*/
printf(":%d ",*(p->info));
}
}
p=p->nextarc;
}
printf("\n");
}
}
/* .........................*/
/* .........................*/
#include "pubuse.h"
#define MAX_NAME 3 /* 顶点字符串的最大长度+1 */
typedef int InfoType; /* 存放网的权值*/
typedef char VertexType[MAX_NAME]; /* 字符串类型*/
#include"ALGraphDef.h"
#include"ALGraphAlgo.h"
void print(char *i)
{
    printf("%s ",i);
}
void main()
{
 int i,j,k,n;
 ALGraph g;
 VertexType v1,v2;
 printf("请选择有向图\n");
 CreateGraph(g);
 Display(g);
 printf("深度优先搜索的结果:\n");
 DFSTraverse(g,print);
 printf("广度优先搜索的结果:\n");
 BFSTraverse(g,print);
 DestroyGraph(g); /* 销毁图*/
}
Ⅸ C语言 图的遍历
思路:
以邻接表或邻接矩阵为存储结构,实现连通无向图的深度和广度优先遍历。以用户指定的结点为起始点
,分别输出每种遍历下的结点访问序列和相应的生成树的边集。
设图的结点不超过30个,每个结点用一个编号表示。通过输入图的全部边输入一个图,每个边为一个数对
可以对边的输入顺序作出某种限制。注意,生成树和生成边是有向边,端点顺序不能颠倒。
