Skip to main content

Understanding and Implementing a Complete Graph in C++ (DSA)

A hands-on breakdown of Complete Weighted Undirected Graphs using C++ STL Adjacency Lists.

Updated 3 min readMarkdown
Part of seriesDSA

While learning Data Structures and Algorithms (DSA), Graphs are one of the most versatile topics you will encounter鈥攑owering everything from Google Maps to social networks. Today, I learned and implemented a Complete Weighted Undirected Graph in C++ using an Adjacency List, modeling a network of 5 Indian states.

Here is everything you need to understand the concept, along with the full C++ implementation and output.


Key Concepts to Understand

Before diving into the code, here are the core ideas behind this implementation:

  • Vertices (Nodes) & Edges: Vertices are the entities (in our case, states like Delhi, Punjab, etc.), and edges are the connections between them.
  • Complete Graph (\(K_n\)): A graph where every single vertex is directly connected to every other vertex.
  • Total Edges Formula: For an undirected complete graph with $n$ vertices, the total number of unique edges is E = n(n - 1) / 2. Since our example has n = 5 states, there are (5 * 4) / 2 = 10 unique connections.
  • Undirected Graph: Connections go both ways. If Delhi is connected to Punjab, then Punjab is automatically connected to Delhi.
  • Weighted Graph: Every edge carries a numerical value (weight), which can represent distance, travel cost, or network latency.
  • Adjacency List Representation: Instead of a 2D matrix, we use a map where each key is a vertex, and its value is a vector of pair<string, int> storing (neighbor, weight). Using std::map also keeps the vertices sorted alphabetically.

C++ Implementation

#include <bits/stdc++.h>
#include <map>
#include <utility>

using namespace std;

class Graph {
    public:
    map<string, vector<pair<string, int>>> m;

    void connect(string v1, string v2, int w) {
        m[v1].push_back({v2, w});
        m[v2].push_back({v1, w});
    }

    void dis() {
        for (auto key : m) {
            cout << key.first << " -> ";
            for (auto val : key.second) {
                cout << "(" << val.first << "," << val.second << ") ";
            }
            cout << endl;
        }
    }
};

int main() {
    Graph g;
    g.connect("Delhi", "Punjab", 10);
    g.connect("Delhi", "Karanataka", 20);
    g.connect("Delhi", "Telangana", 10);
    g.connect("Delhi", "TamilNadu", 15);
    g.connect("Punjab", "TamilNadu", 50);
    g.connect("Punjab", "Telangana", 30);
    g.connect("Punjab", "Karanataka", 25);
    g.connect("Karanataka", "Telangana", 35);
    g.connect("Karanataka", "TamilNadu", 40);
    g.connect("Telangana", "TamilNadu", 40);

    g.dis();
}

How the Code Works

  1. Data Structure (m): map<string, vector<pair<string, int>>> maps each state name to a dynamic list of its connected states and their respective weights.
  2. connect(v1, v2, w): Because the graph is undirected, it pushes {v2, w} into v1's list and {v1, w} into v2's list.
  3. dis(): Iterates through the map and prints each vertex followed by all its (neighbor, weight) pairs.

Output

Delhi -> (Punjab,10) (Karanataka,20) (Telangana,10) (TamilNadu,15) 
Karanataka -> (Delhi,20) (Punjab,25) (Telangana,35) (TamilNadu,40) 
Punjab -> (Delhi,10) (TamilNadu,50) (Telangana,30) (Karanataka,25) 
TamilNadu -> (Delhi,15) (Punjab,50) (Karanataka,40) (Telangana,40) 
Telangana -> (Delhi,10) (Punjab,30) (Karanataka,35) (TamilNadu,40) 

Notice how each of the 5 states has exactly 4 neighbors (n - 1), confirming that this is a complete graph, and the output is sorted alphabetically by state name thanks to std::map.


Complexity Analysis

Operation Time / Space Complexity Why?
Adding an Edge (connect) O(log V) std::map lookup takes O(log V); push_back is O(1) amortized.
Displaying Graph (dis) O(V + E) -> O(V^2) Visits every vertex and edge; in a complete graph, E = O(V^2).
Space Complexity O(V + E) -> O(V^2) Stores V keys and 2E total neighbor entries.

Tags: #DSA #Cpp #GraphTheory #DataStructures #Algorithms #CodingJourney #100DaysOfCode #Hashnode

About the author

No comments yet. Be the first to comment.