建立有向加权图和最短路径算法

时间:2015-06-01 08:47:23

标签: c++ algorithm graph shortest-path

嘿,我在c ++中有一个图表,只用这段代码描述。这是我在大学设置的问题。

#include <iostream>
using namespace std;
const int N = 10;

struct elem
{
    char key;
    elem *next;
} *g[N];

void init(elem *g[N])
{
    for (int i = 0; i < N; i++)
        g[i] = NULL;
}

int search_node(char c, elem *g[N])
{
    for (int i = 0; i < N; i++)
        if (g[i])
            if (g[i]->key == c)
                return 1;

    return 0;
}

int search_arc(char from, char to, elem *g[N])
{
    if (search_node(from, g) && search_node(to, g))
    {
        int i = 0;

        while (g[i] == NULL || g[i]->key != from) i++;

        elem *p = g[i];

        while (p->key != to && p->next)
            if (p->key == to)
                return 1;
    }

    return 0;
}

void add_node(char c, elem *g[N])
{
    if (search_node(c, g))
        cout << "Node already exists.\n";

    int i = 0;
    while (g[i] && (i < N)) i++;

    if (g[i] == NULL)
    {
        g[i] = new elem;
        g[i]->key = c;
        g[i]->next = NULL;
    }
    else
    {
        cout << "Maximum nodes reached.\n";
    }
}

void add_arc(char from, char to, elem *g[N])
{
    if (search_arc(from, to, g))
        cout << "Arc already exists.\n";
    else
    {
        if (!search_node(from, g))
            add_node(from, g);

        if (!search_node(to, g))
            add_node(to, g);

        int i = 0;
        while (g[i] == NULL || g[i]->key != from) i++;

        elem *p = new elem;
        p->key = to;
        p->next = g[i]->next;

        g[i]->next = p;
    }
}

void del_node(char c, elem *g[N])
{

    if (search_node(c, g))
    {

        int i = 0;
        while (g[i] == NULL || g[i]->key != c)
            i++;
        elem *p, *q = NULL;
        while (g[i])
        {

            p = g[i];
            g[i] = g[i]->next;
            delete p;

        }

        for (int i = 0; i < N; i++)
            if (g[i])
            {

                p = g[i];
                while (p->key != c && p->next)
                {

                    q = p;
                    p = p->next;

                }
                if (p->key == c)
                {

                    q->next = p->next;
                    delete p;

                }

            }

    }
    else
        cout << "\nThe node is not in the graph!" << endl;

}

void print(elem *g[N])
{
    for (int i = 0; i < N; i++)
        if (g[i])
        {
            elem *p = g[i];

            while (p)
            {
                cout << p->key << "\t";
                p = p->next;
            }

            cout << endl;
        }
}

我的图形结构的节点有下一个元素,这些元素是图形数组中的第一个元素是节点,下一个元素是弧。

我必须修改和扩展此代码并创建有向加权图并实现最短路径算法。我不能上课!我知道我应该但我们不被允许。

0 个答案:

没有答案