基于图的深度优先搜索策略(耿7.10)--------西工大noj

​ 代码

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ArcNode{
    int to;
    struct ArcNode *next;
    int w;
}ArcNode;
typedef struct VertexNode
{
    int data;
    ArcNode *arc;
}VertexNode;
typedef struct Graph
{
    int max;
    VertexNode *vertex;
}Graph;
int dream;
int find;
Graph *Create(int n)
{
    Graph *G = (Graph*)malloc(sizeof(Graph));
    G->max = n;
    G->vertex = (VertexNode*)calloc(n+1,sizeof(VertexNode));
    for(int i = 0; i <= n; i++)
    {
        G->vertex[i].arc = NULL;
    }
    return G;
}
int Locate(Graph *G,int x)
{
    int i = 1;
    for(; i<=G->max; i++)
    {
        if(G->vertex[i].data == x)
            break;
    }
    if(i > G->max)
        return -1;
    else
        return i;
}
void Fill_VertexNode(Graph *G, int n)
{
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&G->vertex[i].data);
    }
}
void Add(Graph *G,int x, int y)
{
    int a = Locate(G,x);
    int b = Locate(G,y);
    ArcNode *A = (ArcNode*)malloc(sizeof(ArcNode));
    A->to = b;
    A->next = G->vertex[a].arc;
    G->vertex[a].arc = A;
}
void DFS(Graph *G,int *arr, int x)
{
    if(arr[x]==1)
        return;
    if(G->vertex[x].data == dream)
    {
        for(int i = 0; i <= G->max; i++) arr[i] = 1;
        find = 1;
        return ;
    }
    for(ArcNode *A = G->vertex[x].arc; A; A = A->next)
    {
        if(arr[A->to])
            continue;
        DFS(G,arr,A->to);
    }

}
int DFS_search(Graph*G, int x,int dre)
{
    find = 0;
    x = Locate(G,x);
    dream = dre;
    int *arr = (int *)calloc(G->max+1, sizeof(int));
    for(int i = 0; i <= G->max; i++)
    {
        arr[i] = 0;
    }
    DFS(G,arr,x);
    return find;
}
int main()
{
    int begin, end;
    int n,m;
    scanf("%d%d",&n,&m);
    Graph *G = Create(n);
    Fill_VertexNode(G,n);
    for(int i = 1; i <= m; i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        Add(G,x,y);
    }
    scanf("%d%d",&begin,&end);
    int ret = DFS_search(G,begin,end);
    if(ret) printf("yes");
    else printf("no");
    return 0;
}
/*
4 4
4 2 1 3
1 2
1 3
1 4
2 3
2 3

*/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值