Ⅰ 求大神幫寫一個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個,每個結點用一個編號表示。通過輸入圖的全部邊輸入一個圖,每個邊為一個數對
可以對邊的輸入順序作出某種限制。注意,生成樹和生成邊是有向邊,端點順序不能顛倒。
