7-3 underground maze exploration (30 points) (dfs)

Keywords: network

Tunnel war is a way of fighting against Japanese invaders in the North China Plain during the Anti Japanese war. The tunnel network is the underground works of Fang Lian Fang, Jie Lian Jie and Cun Lian Cun, as shown in the figure below.

While reviewing the arduous war life of our predecessors, we sincerely admire their intelligence. In today's era of peaceful development, for most people, exploring the underpass may be just a game of entertainment or wisdom. This experimental case is to explore the labyrinth of underpass.

Suppose there is a labyrinth of underpasses where the passageways are straight, and there is a light and a switch at all intersections of the passageway (including the end of the passageway). How do you light all the lights in the maze from a certain starting point and return to the starting point?

Input format:

Input the first line to give three positive integers, which respectively represent the number of nodes N (1) of the underground labyrinth

/*Input example 1:

6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5

Output sample 1:

1 2 3 4 5 6 5 4 3 2 1

Input example 2:

6 6 6
1 2
1 3
2 3
5 4
6 5
6 4

Output sample 2:

6 4 5 4 6 0*/
#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
int n,m,s,mp[1005][1005],j,path[3000],vis[1005];
void dfs(int start)
{
    int i;
    for(i = 1; i <= n; i++)
    {
        if(mp[start][i]==1&&!vis[i])
        {
            vis[i] = 1;
            path[j++] = i;

            dfs(i);
            path[j++] = start;

        }
    }
}
int main()
{
    memset(path,0,sizeof(path));
    memset(vis,0,sizeof(vis));
    memset(mp,INF,sizeof(mp));
    int i;
    scanf("%d%d%d",&n,&m,&s);
    for(i = 0; i < m; i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        mp[u][v] = 1;
        mp[v][u] = 1;
    }
    path[0] = s;
    j++;
    vis[s] = 1;
    dfs(s);
    int flag = 1;
    for(i = 1; i <= n; i++)
    {
        if(vis[i]==0)
        {
            flag = 0;
            break;
        }
    }
    if(!flag)
    {
        for(i = 0; i < j; i++)
        {
            if(i==0)printf("%d",path[i]);
            else printf(" %d",path[i]);
        }
        printf(" 0");
    }
    else
    {
        for(i = 0; i < j; i++)
        {
            if(i==0)printf("%d",path[i]);
            else printf(" %d",path[i]);
        }
    }
    puts("");
    return 0;
}

Posted by Skawn on Sat, 04 Apr 2020 20:52:57 -0700