#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define maxlen 100
typedef struct node* Node;
struct node{
int n;
Node next;
};
typedef struct vnode{
int n;
Node firstedge;
}*Vnode;
typedef struct{
int n,e;
struct vnode Ad[maxlen];
}*Adgraph;//邻接表
typedef struct{
int ele[maxlen];
int n,e;
int mat[maxlen][maxlen];
}*matrix;
int visited[maxlen];
int Tree[maxlen][maxlen];
void PrintTreeA(int Tree[maxlen][maxlen],Adgraph G)
{
int x,y;
for(x=0;x<G->n;x++)
{
for(y=0;y<G->n;y++)
{
printf("%d ",Tree[x][y]);
}
printf("\n");
}
}
void PrintTreem(int Tree[maxlen][maxlen],matrix G)
{
int x,y;
for(x=0;x<G->n;x++)
{
for(y=0;y<G->n;y++)
{
printf("%d ",Tree[x][y]);
}
printf("\n");
}
}
void createm(matrix G)//创建矩阵
{
FILE* file = fopen("graph.txt", "r");
int i,j,x,y;
fscanf(file,"%d %d",&G->n,&G->e);
for(i=0;i<G->n;i++)
G->ele[i]=i;
for(i=0;i<G->n;i++)
for(j = 0;j<G->n;j++)
G->mat[i][j] = 0;
for(j=0;j<G->e;j++)
{
fscanf(file,"%d %d",&x,&y);
G->mat[x][y] =1;
G->mat[y][x] =1;
}
fclose(file);
}
void DFSm1(matrix G,int i)//邻接矩阵递归DFS
{
int j;
printf("%d ",G->ele[i]);
visited[i]=1;
for(j=0;j<G->n;j++)
if(G->mat[i][j]==1&&!visited[j])
{ DFSm1(G,j);
Tree[i][j]=1;
Tree[j][i]=1;}
}
void DFSAd1(Adgraph G,int i)//邻接表递归DFS
{
int j;
printf("%d ",G->Ad[i].n);
visited[i]=1;
Node p = (Node)malloc(sizeof(struct node));
p = G->Ad[i].firstedge;
while(p!= NULL)
{
if(!visited[p->n])
{
DFSAd1(G,p->n);
Tree[p->n][i]=1;
Tree[i][p->n]=1;
}
p=p->next;
}
}
void DFSm2(matrix G,int v)//邻接矩阵非递归DFS
{
int STACK[maxlen];
int top = maxlen;
STACK[--top]=v;
while(top!=maxlen)
{
int w = STACK[top++];
if(!visited[w])
{
printf("%d ",G->ele[w]);
vis
哈工大数据结构实验三:图的邻接表和邻接矩阵DFS与BFS
最新推荐文章于 2024-07-25 19:28:17 发布