哈工大数据结构实验三:图的邻接表和邻接矩阵DFS与BFS

#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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值