哈密顿路径

#include <iostream>

using namespace std;

struct Graph{
    int vertexs;
    int **adj;
};

struct Edge{
    int v;
    int w;
};

void GraphInit(Graph* G, int v)
{
    G->vertexs = v;
    G->adj = new int*[v];
    for (int i = 0; i < v; ++i)
        G->adj[i] = new int[v];

    for (int i = 0; i < v; ++i)
        for (int j = 0; j < v; ++j)
            G->adj[i][j] = 0;
}

void GraphInsertEdge(Graph* G, Edge e)
{
    G->adj[e.v][e.w] = 1;
    G->adj[e.w][e.v] = 1;
}


void GraphPrint(Graph* G)
{
    for (int i = 0; i < G->vertexs; ++i){
        for (int j = 0; j < G->vertexs; ++j)
            cout << G->adj[i][j] << " ";
        cout << endl;
    }
}

//哈密顿路径
static int visited[10] = {0};

int PathH(Graph* G, int v, int w, int d)
{
    int t;
    if (v == w){
        if (d == 0) return 1;
        else return 0;
    }

    visited[v] = 1;
    for (t = 0; t < G->vertexs; ++t)
        if (G->adj[v][t] == 1)
            if (visited[t] == 0)
                if (PathH(G, t, w, d-1)) return 1;
    visited[v] = 0;
    return 0;
}


int main()
{
    Graph G;
    GraphInit(&G, 7);

    Edge e[10] = {{0, 5}, {0, 1}, {0, 2}, {0, 6},
                    {1, 2},
                    {2, 3}, {2, 4},
                    {3, 4},
                    {4, 5}, {4, 6}};

    for (int i = 0; i < 10; ++i)
        GraphInsertEdge(&G, e[i]);

    GraphPrint(&G);

    cout << PathH(&G, 0, 6, G.vertexs-1) << endl;

    return 0;
}
原文地址:https://www.cnblogs.com/shamoof/p/4784849.html