哈密顿路径_检查图形是否为哈密顿量(哈密顿路径)

本文介绍了如何判断一个图是否为哈密顿图,提供了一种算法思路:从源节点出发,遍历未访问的相邻节点,当节点数等于图的顶点数时,检查是否存在回源路径。若不存在则标记为未访问并继续过程。最终,若无法找到回源路径则判断为非哈密顿图。
摘要由CSDN通过智能技术生成

哈密顿路径

Problem Statement:

问题陈述:

Given a graph G. you have to find out that that graph is Hamiltonian or not.

给定图G。 您必须找出该图是否为哈密顿量

Example:

例:

Input:

输入:

hamiltonian path

Output: 1

输出1

Because here is a path 0 → 1 → 5 → 3 → 2 → 0 and 0 → 2 → 3 → 5 → 1 → 0

因为这里是路径0→1→5→3→2→0和0→2→3→5→1→0

Algorithm:

算法:

To solve this problem we follow this approach:

为了解决这个问题,我们采用以下方法:

  1. We take the source vertex and go for its adjacent not visited vertices.

    我们获取源顶点,并寻找其相邻的未访问顶点。

  2. Whenever we find a new vertex we make it source vertex and we repeat step 1.

    每当我们找到一个新顶点时,就将其设为源顶点,然后重复步骤1。

  3. When a vertex count is equal to the vertex number then we check that from vertex is there any path to the source vertex. If there is exist a path to the source vertex then we will mark it and if not then make that vertex as unmarked and continue the process.

    当顶点数等于顶点数时,我们检查从顶点开始是否存在到源顶点的任何路径。 如果存在到源顶点的路径,那么我们将对其进行标记,如果没有,则将该顶点设为未标记并继续该过程。

  4. If there is no such path then we say NO.

    如果没有这样的路径,那么我们说不。

检查图是否为哈密顿的C ++实现 (C++ Implementation to check a graph is Hamiltonian or not )

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

void addedge(list<int>* g, int u, int v)
{
    g[u].push_back(v);
    g[v].push_back(u);
}

int hamiltonian(list<int>* g, int v, int s, int& count, bool* vis, int& h)
{
    if (count > 1 && s == 0) {
        h = 1;
        return 1;
    }
    list<int>::iterator it;
    for (it = g[s].begin(); it != g[s].end(); it++) {
        if (!vis[*it]) {
            vis[*it] = true;
            count++;
            if (count == v) {
                vis[0] = false;
            }
            hamiltonian(g, v, *it, count, vis, h);
            vis[0] = true;
            vis[*it] = false;
            count--;
        }
    }
    return 0;
}

int main()
{
    int num;
    cin >> num;
    for (int i = 0; i < num; i++) {
        int v, e;
        cin >> v >> e;
        list<int> g[v];
        int x, y;
        for (int j = 0; j < e; j++) {
            cin >> x >> y;
            addedge(g, x, y);
        }
        bool vis[v];
        memset(vis, false, sizeof(vis));
        int count = 1;
        vis[0] = true;
        int h = 0;
        hamiltonian(g, v, 0, count, vis, h);
        cout << h << endl;
    }
    return 0;
}

Output

输出量

1
5
8
0 1
0 2
1 2
1 3
1 4
3 4
3 2
2 4
1


翻译自: https://www.includehelp.com/icp/check-a-graph-is-hamiltonian-or-not-hamiltonian-path.aspx

哈密顿路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值