Значение мусора в выводе графика

Я иду и пытаюсь отладить каждую строку этого кода, но не могу понять, почему один узел имеет значение мусора, а все остальные работают. У меня есть ощущение, что это связано с моей функцией печати графика. В зависимости от того, как я изменю свою функцию печати, разные узлы будут иметь значения мусора.

Вход

  • 10 (узлы)
  • 8, 1, 3, 9, 5, 7, 3, 9, 9, 9 (стоимость i-го узла)
  • 11 (ребра)
  • Вершины u к v (5 8), (1 10), (4 1), (6 10), (7 3), (6 4), (5 10), (3 6), (4 9), (3 5), (10 8)

Вот что я вижу в выводе, когда строю график и распечатываю его:

Список смежности вершин 1 -> -397409888 (стоимость 9)

Список смежности вершины 2

Список смежности вершин 3 -> 5 (стоимость 5) -> 6 (стоимость 7)

Список смежности вершин 4 -> 9 (стоимость 9) -> 1 (стоимость 8)

Список смежности вершин 5 -> 10 (стоимость 9) -> 8 (стоимость 9)

Список смежности вершин 6 -> 4 (стоимость 9) -> 10 (стоимость 9)

Список смежности вершин 7 -> 3 (стоимость 3)

Список смежности вершины 8

Список смежности вершины 9

Список смежности вершин 10 -> 8 (стоимость 9)

Обратите внимание, что вершина 1 имеет значение мусора -397409888, когда оно должно быть 10. Это происходит только в том случае, если последний узел имеет какие-либо прямые ребра. В этом случае, если ребро (10,8) не существовало, то вывод идеален. Любая помощь будет оценена.

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int vertex;
    int visited;
    int cost;
    struct node* next;
};

struct node* createNode(int v, int w);

struct Graph
{
    int numVertices;
    struct node** adjLists;
};

struct Graph* createGraph(int);
void addEdge(struct Graph*, int, int, int);
void printGraph(struct Graph*);
void DFS(struct Graph*, int);

// DFS function to recur on all nodes
void DFS(struct Graph* graph, int vertex) {
    struct node* adjList = graph->adjLists[vertex];
    struct node* temp = adjList;

    // Mark as visited and print
    temp->visited = 1;
    printf("Visited %d \n", vertex);

    // While there are more nodes connected
    while(temp!=NULL) {
        int connectedVertex = temp->vertex;

        // If the adjacent vertex is unvisited recur
        if(temp->visited == 0) {
            DFS(graph, connectedVertex);
        }
        temp = temp->next;
    }
}

// Function to create a node
struct node* createNode(int v, int w)
{
    struct node* newNode = malloc(sizeof(struct node));
    newNode->vertex = v;
    newNode->cost = w;
    newNode->visited = 0;
    newNode->next = NULL;
    return newNode;
}

// Function to generate the directed and connected graph
struct Graph* createGraph(int vertices)
{
    struct Graph* graph = malloc(sizeof(struct Graph));
    graph->numVertices = vertices;

    graph->adjLists = malloc(vertices * sizeof(struct node*));

    int i;
    for (i = 0; i < vertices; i++) {
        graph->adjLists[i] = NULL;
    }

    return graph;
}

// Function to add edges to the graph
void addEdge(struct Graph* graph, int src, int w, int dest)
{
    // Add edge from src to dest
    struct node* newNode = createNode(dest, w);
    newNode->next = graph->adjLists[src];
    graph->adjLists[src] = newNode;
}


// Function to print the graph
void printGraph(struct Graph* graph)
{
    int v;
    for (v = 1; v <= graph->numVertices; v++)
    {
        struct node* temp = graph->adjLists[v];
        printf("\nAdjacency list of vertex %d\n" , v);
        while (temp)
        {
            printf("-> %d (cost %d)\n", temp->vertex, temp->cost);
            temp = temp->next;
        }
        printf("\n");
    }
}

void printArray(int arr[], int len)
{
    int i;
    for (i = 0; i <= len; i++){
        printf("%d\n", arr[i]);
    }
}

// Driver program to test above functions 
int main() 
{
    // Open file
    FILE *file;
    file = fopen("CLionProjects/untitled1/txt.txt", "r");

    // Determine input length
    fseek(file, 0, SEEK_END);
    unsigned long len = ((unsigned long)ftell(file)/2);
    rewind(file);

    // Read input into array
    int arr[len];
    int i;
    for (i = 0; i <= len; i++)
    {
        fscanf(file, "%d", &arr[i]);
    }

    // Close File
    fclose(file);

    // Generate array of costs & roads
    int weights[arr[0]];
    int roads = arr[arr[0]+1];
    int j = 0;
    for (i = 1; i <= arr[0]; i++)
    {
        weights[j] = arr[i];
        j++;
    }

    // Generate graph with the given input
    int V = arr[0];
    struct Graph* graph = createGraph(V);
    i = 2 + V;
    for (j = 1 ; j <= roads; j++)
    {
        addEdge(graph, arr[i], weights[(arr[i+1])-1], arr[i+1]);
        i = i + 2;
    }

    printGraph(graph);

    return 0; 
}

0 ответов

Другие вопросы по тегам