Euler circuit in output undirected graph

In a graph, there is a path that passes through each edge exactly once, and reaches the first vertex at the last vertex. Such a path is called an Euler circuit .

#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 200;

struct stack
{
    
    
    int top, node[maxn];
} s;
int e[maxn][maxn], vertex;

void dfs(int x)
{
    
    
    s.node[++s.top] = x;
    for (int i = 0; i < vertex; i++) {
    
    
        if (e[i][x] > 0) {
    
    
            e[i][x] = e[x][i] = 0;  //删除这条边
            dfs(i);
            break;
        }
    }
}

void fleury(int x)
{
    
    
    int flag;
    s.top = 0;
    s.node[s.top] = x;
    while (s.top >= 0) {
    
    
        flag = 0;
        for (int i = 0; i < vertex; i++) {
    
    
            if (e[s.node[s.top]][i] > 0) {
    
    
                flag = 1;
                break;
            }
        }
        if (!flag)
            printf("%d ", s.node[s.top--] + 1);
        else
            dfs(s.node[s.top--]);
    }
    puts("");
}

int main( )
{
    
    
    int x, y, edge, degree, num = 0, start = 0;
    scanf("%d%d", &vertex, &edge);
    memset(e, 0, sizeof(e));
    for (int i = 0; i < edge; i++) {
    
    
        scanf("%d%d", &x, &y);
        e[x - 1][y - 1] = e[y - 1][x - 1] = 1;
    }
    for (int i = 0; i < vertex; i++) {
    
    
        degree = 0;
        for (int j = 0; j < vertex; j++)
            degree += e[i][j];
        if (degree & 1) {
    
    
            start = i;
            num++;
        }
    }
    if (num == 0 || num == 2)
        fleury(start);
    else
        printf("No Euler path\n");
    return 0;
}

/*
12 21
1 3
1 4
2 3
3 4
4 5
2 8
3 9
4 10
8 9
9 10
10 11
9 12
10 12
6 3
6 9
3 7
9 7
7 4
7 10
4 11
10 5
*/

Reference blog: https://blog.csdn.net/u011466175/article/details/18861415

Guess you like

Origin blog.csdn.net/qq_18431031/article/details/108287202