struct Stack//栈的设计
{
int buf[20];
int n;
};
Stack *CreatStack()//创建空栈
{
Stack *s;
s=(Stack*)malloc(sizeof(Stack));
s->n=-1;
return s;
}
int pop(Stack*s)//出栈
{
int tmp;
tmp=s->buf[s->n];
s->n--;
return tmp;
}
void push(Stack*s,int x)//入栈
{
s->n++;
s->buf[s->n]=x;
}
int IsEmpty(Stack*s)//判断栈是否为空
{
if(s->n==-1)
return 1;
else
return 0;
}
struct Node//建立节点
{
int data;
struct Node*next;
};
struct queue//队列的定义
{
Node*front;
Node*rear;
};
queue*CreatQueue()//创建空队列
{
queue *q;
q=(queue*)malloc(sizeof(queue));
Node*h;
h=(Node*)malloc(sizeof(Node));
q->front=q->rear=h;
return q;
}
int IsEmptyQ(queue*q)//判断队列是否为空
{
if(q->front==q->rear)
return 1;
else
return 0;
}
void pushQ(queue*q,int x)//入队列
{
Node *tmp;
tmp=(Node*)malloc(sizeof(Node));
tmp->data=x;
tmp->next=NULL;
q->rear->next=tmp;
q->rear=tmp;
}
int popQ(queue*q)//出队列
{
Node *tmp;
tmp=q->front;
q->front=q->front->next;
free(tmp);
tmp=NULL;
return q->front->data;
}
#include<stdio.h>
#include<stdlib.h>
#include"data.h"
#include"queue.h"
#include<string.h>
int visit[20];//访问记录
struct Graph//图的定义
{
int n;//顶点的个数
int ver[20];//记录顶点
int adj[20][20];//邻接矩阵
};
void InitiateGraph(Graph*g)//初始化图
{
memset(g,0,sizeof(Graph));
g->n=-1;
printf("请输入顶点:\n");
while(scanf("%d",&g->ver[++g->n]));
while(getchar()!='\n');
int i=0;
for(i=0;i<g->n;i++)
{
printf("V%d ",g->ver[i]);
}
printf("\n");
}
int LocateVer(Graph*g,int v)//寻找某节点的位置
{
int i;
for(i=0;i<g->n;i++)
if(g->ver[i]==v)
{
return i;
break;
}
return 0;
}
void InputEdge(Graph*g)//输入边
{
int vex1,vex2;
int i,j;
printf("input edge(i,j):\n");
while(scanf("(%d,%d)",&vex1,&vex2))//任意字母键结束
{
getchar();
i = LocateVer(g,vex1);
j = LocateVer(g,vex2);
g->adj[i][j]=g->adj[j][i] = 1;
}
int m,n;
for(m=0;m<g->n;m++)
{
for(n=0;n<g->n; n++)
{
printf("%d ",g->adj[m][n]);
}
printf("\n");
}
}
int visit_all(Graph *pG)
{
int i=0;
for(i=0;i<pG->n;i++)
{
if(visit[i]!=1)
break;
}
if(i == pG->n)
return 1;
else
return 0;
}
int DFS(Graph *pG,int v)
{
Stack *stack;
int i=0;
stack=CreatStack();
push(stack,pG->ver[v]);
visit[v] = 1;
printf("V%d ",pG->ver[v]);
while(!IsEmpty(stack) || !visit_all(pG))
{
for(i = 0;i < pG->n;i ++)
{
if(visit[i] == 0 && pG->adj[v][i] == 1)
break;
}
if(i == pG->n)
{
v = pop(stack);
}
else
{
v = i;
push(stack,pG->ver[v]);
visit[v] = 1;
printf("V%d ",pG->ver[v]);
}
}
printf("\n");
return 0;
}
int BFS(Graph *pG,int v)
{
queue *q= CreatQueue();
int i=0;
memset(&visit,0,sizeof(visit));
pushQ(q,v);
visit[v] = 1;
while(!IsEmptyQ(q))
{
v = popQ(q);
printf("V%d ",pG->ver[v]);
for(i=0;i<pG->n;i++)
{
if(visit[i] == 0 && pG->adj[v][i]==1)
{
pushQ(q,i);
visit[i] = 1;
}
}
}
printf("\n");
return 0;
}
int main()
{
Graph g;
InitiateGraph(&g);
InputEdge(&g);
DFS(&g,0);
BFS(&g,0);
return 0;
}