lundi 14 novembre 2022

function printGraph prints too many Nodes

I'm trying to make a program that print the nodes and the edges from graph and shows the shortest path from declared node to all others. The problem is that the print function I create prints too many Nodes with name 0 and edge with weight 0 and I don't know why. Here is the function to add edge in the nodes and function that should be print the graph correctly.

`

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

void addEdge(vector<vector<pair<int, int>>>& graph, int u, int v, int w)
{
    graph[u].push_back(make_pair(v, w));
    graph[v].push_back(make_pair(u, w));
}

void printGraph(vector<vector<pair<int, int>>> adj, int V)
{
    int v, w;
    for (int u = 0; u < V; u++)
    {
        cout << "Node " << u << " makes an edge with \n";
        for (auto it = adj[u].begin(); it != adj[u].end(); it++)
        {

            v = it->first;
            w = it->second;
            cout << "\tNode " << v << " with edge weight ="
                << w << "\n";
        }
        cout << "\n";
    }
}

int main()
{
    vector<vector<pair<int, int>>> graph(9, vector<pair<int, int>>(9));
    addEdge(graph, 0, 1, 4);
    addEdge(graph, 0, 7, 8);
    printGraph(graph,1);
    return 0;
}

`

I tried to find the similar problem but without success.

Aucun commentaire:

Enregistrer un commentaire