Open In App

Adjacency List Generation from Edge Connections

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of undirected edge connections of size E, create an adjacency list for a graph with V nodes and E edges following 0-based indexing and return the adjacency list.

Examples:

Input: V = 4, E = 5, edges = [[0, 1], [1, 2], [2, 3], [0, 2], [1, 3]]
Output: [[1, 2], [0, 2, 3], [1, 3, 0], [2, 1]]
Explanation:

  • Node 0 is connected to 1 2
  • Node number 1 is connected to 0 2 3
  • Node 2 is connected to 1 3 0
  • Node 3 is connected to 2 1

Input: V = 4, E = 3, edges = [[0, 3], [0, 2], [2, 1]]
Output: [[2, 3], [2], [0, 1], [0]]
Explanation:

  • Node 0 is connected to 2 and 3.
  • Node 1 is only connected to 2.
  • Node 2 is connected to 0 and 1.
  • Node 3 is only connected to 0.

Approach: To solve the problem follow the below idea:

The intuition is to traverse the edge list and for every edge [u, v], push vertex v to the list at index u and push vertex u to the list at index v.

Follow the below steps to implement the idea:

  • Initialize a 2-D vector adj[V][] to store the adjacency list.
  • Traverse the edge list edges[], and for every edge [u, v],
    • Insert vertex v to the list at index u, that is adj[u]
    • Insert vertex u to the list at index v, that is adj[v]
  • Print the 2-D vector adj[][].

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void getAdjacencyList(vector<pair<int, int> >& edges,
                      vector<vector<int> >& adj)
{
    for (auto edge : edges) {
        // For edge [u, v], push v to the
        // list at index u
        adj[edge.first].push_back(edge.second);
 
        // For edge [u, v], push u to the
        // list at index v
        adj[edge.second].push_back(edge.first);
    }
}
 
// Drivers code
int main()
{
    int V = 5;
    vector<vector<int> > adj(V);
    vector<pair<int, int> > edges{ { 0, 1 }, { 0, 4 },
                                   { 4, 1 }, { 4, 3 },
                                   { 1, 3 }, { 1, 2 },
                                   { 3, 2 } };
    getAdjacencyList(edges, adj);
 
    // Print the 2-D vector adj
    for (int i = 0; i < V; i++) {
        cout << "{";
        for (int j = 0; j < adj[i].size(); j++) {
            cout << adj[i][j];
            if (j + 1 < adj[i].size()) {
                cout << ", ";
            }
        }
        cout << "}";
        if (i < V - 1) {
            cout << ", ";
        }
        cout << endl;
    }
    return 0;
}


Java




// Java code for the above approach
 
import java.util.*;
 
class GFG {
    static void getAdjacencyList(int[][] edges,
                                 List<List<Integer>> adj)
    {
        for (int[] edge : edges) {
            // For edge [u, v], push v to the
            // list at index u
            adj.get(edge[0]).add(edge[1]);
 
            // For edge [u, v], push u to the
            // list at index v
            adj.get(edge[1]).add(edge[0]);
        }
    }
    // Drivers code
    public static void main(String[] args)
    {
        int V = 5;
        List<List<Integer>> adj = new ArrayList<>();
 
        for (int i = 0; i < V; i++) {
            adj.add(new ArrayList<>());
        }
 
        int[][] edges
            = { { 0, 1 }, { 0, 4 }, { 4, 1 }, { 4, 3 },
                { 1, 3 }, { 1, 2 }, { 3, 2 } };
        getAdjacencyList(edges, adj);
 
        // Print the 2-D vector adj
        for (int i = 0; i < V; i++) {
            System.out.print("{");
 
            for (int j = 0; j < adj.get(i).size(); j++) {
                System.out.print(adj.get(i).get(j));
 
                if (j + 1 < adj.get(i).size()) {
                    System.out.print(", ");
                }
            }
 
            System.out.print("}");
 
            if (i < V - 1) {
                System.out.print(", ");
            }
 
            System.out.println();
        }
    }
}
 
// This code is contributed by ragul21


Python3




# Python Implementation
def get_adjacency_list(edges, adj):
    for edge in edges:
        # For edge [u, v], append v to the list at index u
        adj[edge[0]].append(edge[1])
 
        # For edge [u, v], append u to the list at index v
        adj[edge[1]].append(edge[0])
 
# Driver code
if __name__ == "__main__":
    V = 5
    adj = [[] for _ in range(V)]
    edges = [(0, 1), (0, 4), (4, 1), (4, 3), (1, 3), (1, 2), (3, 2)]
    get_adjacency_list(edges, adj)
 
    # Print the 2-D list adj
    for i in range(V):
        print("[", end="")
        for j in range(len(adj[i])):
            print(adj[i][j], end="")
            if j + 1 < len(adj[i]):
                print(", ", end="")
        print("]", end="")
        if i < V - 1:
            print(", ", end="")
        print()
# This code is contributed by Tapesh (tapeshdua420)


C#




using System;
using System.Collections.Generic;
 
class Graph
{
    static void GetAdjacencyList(List<int>[] adj, List<Tuple<int, int>> edges)
    {
        foreach (var edge in edges)
        {
            // For edge (u, v), append v to the list at index u
            adj[edge.Item1].Add(edge.Item2);
 
            // For edge (u, v), append u to the list at index v
            adj[edge.Item2].Add(edge.Item1);
        }
    }
 
    static void Main()
    {
        int V = 5;
        List<int>[] adj = new List<int>[V];
        for (int i = 0; i < V; i++)
        {
            adj[i] = new List<int>();
        }
 
        List<Tuple<int, int>> edges = new List<Tuple<int, int>>
        {
            Tuple.Create(0, 1),
            Tuple.Create(0, 4),
            Tuple.Create(4, 1),
            Tuple.Create(4, 3),
            Tuple.Create(1, 3),
            Tuple.Create(1, 2),
            Tuple.Create(3, 2)
        };
 
        GetAdjacencyList(adj, edges);
 
        // Print the 2-D list adj
        for (int i = 0; i < V; i++)
        {
            Console.Write("[");
            for (int j = 0; j < adj[i].Count; j++)
            {
                Console.Write(adj[i][j]);
                if (j + 1 < adj[i].Count)
                {
                    Console.Write(", ");
                }
            }
            Console.Write("]");
            if (i < V - 1)
            {
                Console.Write(", ");
            }
            Console.WriteLine();
        }
    }
}


Javascript




// Function to create an adjacency list from a list of edges
function getAdjacencyList(edges, V) {
    const adj = new Array(V).fill().map(() => []);
 
    for (const [u, v] of edges) {
        adj[u].push(v);
        adj[v].push(u);
    }
 
    return adj;
}
 
// Driver Code
const V = 5;
const adj = new Array(V).fill().map(() => []);
 
const edges = [
    [0, 1],
    [0, 4],
    [4, 1],
    [4, 3],
    [1, 3],
    [1, 2],
    [3, 2]
];
 
const adjacencyList = getAdjacencyList(edges, V);
 
// Print the 2-D vector adj
for (let i = 0; i < V; i++) {
    console.log(`{${adjacencyList[i].join(', ')}}${i < V - 1 ? ', ' : ''}`);
}


Output

{1, 4}, 
{0, 4, 3, 2}, 
{1, 3}, 
{4, 1, 2}, 
{0, 1, 3}









Time Complexity: O(|V| + |E|), where V is the total number of vertices and E is the total number of edges.
Auxiliary Space: O(|V| + |E|) to store the adjacency list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads