Open In App

Determining topology formed in a Graph

Improve
Improve
Like Article
Like
Save
Share
Report

Given a graph containing n edges. The task is to find the topology formed by the given set of edges in that graph.

Examples:

Input: edges = [(1, 2), (2, 3), (3, 1)]
Output: “linear”
Explanation: This test case contains three edges that are connected end-to-end, forming a linear topology.

Input: edges = [(1, 2), (1, 3), (1, 4), (1, 5)]
Output: “star”
Explanation: This test case contains four edges that are all connected to a central node (1), forming a star topology.

Input: edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)]
Output: “ring”
Explanation: This test case contains five edges that are connected in a circular fashion, forming a ring topology.

Input: edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1), (1, 3), (2, 4), (3, 5), (4, 6)]
Output: “mesh”
Explanation: This test case contains 10 edges that connect all of the nodes in a complex web, forming a mesh topology.

Approach: To solve the problem follow the below Approach:    

To determine the topology formed by a given set of edges, you will need to analyze the connectivity of the edges and identifies the overall shape or structure that they form. This approach first creates a list of edges and an empty dictionary to store the connections for each node. It then iterates over the edges and updates the connections dictionary, keeping track of which nodes are connected to which other nodes. Finally, it determines the topology based on the number and arrangement of the connections in the dictionary, and prints the result.

Here are the steps that are followed in the pseudocode:

  • Create a list of edges and initialize a dictionary to store the connections for each node.
  • Iterate over the edges and update the connections dictionary. For each edge, add the other node to the list of connections for each of the two nodes that are connected by the edge.
  • Determine the topology based on the number and arrangement of the connections in the dictionary. There are four possible cases:
    • If all of the nodes have exactly two connections, the topology is linear.
    • If all of the nodes have exactly one connection, the topology is star.
    • If all of the nodes have exactly two connections, and the first and last edges are connected end-to-end, the topology is ring.
    • If none of the other cases apply, the topology is mesh.
  • Print the topology.

This code assumes that the input will be a list of edges represented as tuples, where each tuple contains the two nodes that are connected by the edge. The edges are assumed to be undirected, meaning that the order of the nodes in the tuple does not matter. The program will work correctly for any set of edges that meet these assumptions.

Below is the implementation of the above approach:

C++14




#include <bits/stdc++.h>
using namespace std;
 
string findTopology(vector<vector<int> >& edges)
{
 
  // Initialize a dictionary to store the
  // connections for each node
  unordered_map<int, vector<int> > connections;
 
  // Iterate over the edges and update
  // the connections dictionary
  for (vector<int>& edge : edges) {
    int node1 = edge[0];
    int node2 = edge[1];
    if (!connections.count(node1)) {
      vector<int> nodes;
      nodes.push_back(node2);
      connections[node1] = nodes;
    }
    else {
      connections[node1].push_back(node2);
    }
    if (!connections.count(node2)) {
      vector<int> nodes;
      nodes.push_back(node1);
      connections[node2] = nodes;
    }
    else {
      connections[node2].push_back(node1);
    }
  }
 
  // Determine the topology based
  // on the connections
  bool isLinear
    = all_of(connections.begin(), connections.end(),
             [](auto& nodes) {
               return nodes.second.size() == 2;
             });
 
  bool isStar
    = all_of(connections.begin(), connections.end(),
             [](auto& nodes) {
               return nodes.second.size() == 1;
             });
 
  bool isRing
    = all_of(connections.begin(), connections.end(),
             [](auto& nodes) {
               return nodes.second.size() == 2;
             })
    && (edges[0][0] == edges[edges.size() - 1][1]);
 
  string topology
    = isLinear
    ? "linear"
    : isStar ? "star" : isRing ? "ring" : "mesh";
 
  // Return the topology
  return topology;
}
 
int main()
{
   
  // Create a list of edges
  vector<vector<int> > edges
    = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 },
       { 5, 6 }, { 6, 1 }, { 1, 3 }, { 2, 4 },
       { 3, 5 }, { 4, 6 } };
  cout << findTopology(edges) << endl;
 
  return 0;
}
 
// This code is contributed by prasad264


Java




import java.util.*;
 
public class Main {
    public static String findTopology(int[][] edges)
    {
        // Initialize a dictionary to store the
        // connections for each node
        Map<Integer, List<Integer> > connections
            = new HashMap<>();
 
        // Iterate over the edges and update
        // the connections dictionary
        for (int[] edge : edges) {
            int node1 = edge[0];
            int node2 = edge[1];
            if (!connections.containsKey(node1)) {
                List<Integer> nodes = new ArrayList<>();
                nodes.add(node2);
                connections.put(node1, nodes);
            }
            else {
                connections.get(node1).add(node2);
            }
            if (!connections.containsKey(node2)) {
                List<Integer> nodes = new ArrayList<>();
                nodes.add(node1);
                connections.put(node2, nodes);
            }
            else {
                connections.get(node2).add(node1);
            }
        }
 
        // Determine the topology based
        // on the connections
        boolean isLinear
            = connections.values().stream().allMatch(
                nodes -> nodes.size() == 2);
        boolean isStar
            = connections.values().stream().allMatch(
                nodes -> nodes.size() == 1);
        boolean isRing
            = connections.values().stream().allMatch(
                  nodes -> nodes.size() == 2)
              && (edges[0][0]
                  == edges[edges.length - 1][1]);
        String topology
            = isLinear ? "linear"
                       : isStar ? "star"
                                : isRing ? "ring" : "mesh";
 
        // Print the topology
        return topology;
    }
 
    public static void main(String[] args)
    {
        // Create a list of edges
        int[][] edges
            = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 },
                { 5, 6 }, { 6, 1 }, { 1, 3 }, { 2, 4 },
                { 3, 5 }, { 4, 6 } };
        System.out.println(findTopology(edges));
    }
}


Python3




def findTopology(edges):
    # Initialize a dictionary to store the
    # connections for each node
    connections = {}
 
    # Iterate over the edges and update
    # the connections dictionary
    for (node1, node2) in edges:
        if node1 not in connections:
            connections[node1] = [node2]
        else:
            connections[node1].append(node2)
        if node2 not in connections:
            connections[node2] = [node1]
        else:
            connections[node2].append(node1)
 
    # Determine the topology based
    # on the connections
    if all(len(v) == 2 for v in connections.values()):
        topology = "linear"
    elif all(len(v) == 1 for v in connections.values()):
        topology = "star"
    elif all(len(v) == 2 for v in connections.values()) and (edges[0][0] == edges[-1][1]):
        topology = "ring"
    else:
        topology = "mesh"
 
    # Print the topology
    return topology
 
 
# Create a list of edges
edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6),
         (6, 1), (1, 3), (2, 4), (3, 5), (4, 6)]
print(findTopology(edges))
 
# this code is contributed by prophet1999


Javascript




function findTopology(edges) {
 
  // Initialize a dictionary to store the
  // connections for each node
  const connections = {};
 
  // Iterate over the edges and update
  // the connections dictionary
  for (let i = 0; i < edges.length; i++) {
    const edge = edges[i];
    const node1 = edge[0];
    const node2 = edge[1];
    if (!connections[node1]) {
      const nodes = [];
      nodes.push(node2);
      connections[node1] = nodes;
    } else {
      connections[node1].push(node2);
    }
    if (!connections[node2]) {
      const nodes = [];
      nodes.push(node1);
      connections[node2] = nodes;
    } else {
      connections[node2].push(node1);
    }
  }
 
  // Determine the topology based
  // on the connections
  const isLinear = Object.values(connections).every(nodes => nodes.length === 2);
 
  const isStar = Object.values(connections).every(nodes => nodes.length === 1);
 
  const isRing = Object.values(connections).every(nodes => nodes.length === 2)
    && (edges[0][0] === edges[edges.length - 1][1]);
 
  const topology = isLinear
    ? "linear"
    : isStar ? "star" : isRing ? "ring" : "mesh";
 
  // Return the topology
  return topology;
}
 
// Create a list of edges
const edges = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ],
                [ 5, 6 ], [ 6, 1 ], [ 1, 3 ], [ 2, 4 ],
                [ 3, 5 ], [ 4, 6 ] ];
 
console.log(findTopology(edges));


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program {
    public static string
    findTopology(List<List<int> > edges)
    {
        // Initialize a dictionary to store the
        // connections for each node
        Dictionary<int, List<int> > connections
            = new Dictionary<int, List<int> >();
 
        // Iterate over the edges and update
        // the connections dictionary
        foreach(List<int> edge in edges)
        {
            int node1 = edge[0];
            int node2 = edge[1];
            if (!connections.ContainsKey(node1)) {
                List<int> nodes = new List<int>();
                nodes.Add(node2);
                connections[node1] = nodes;
            }
            else {
                connections[node1].Add(node2);
            }
            if (!connections.ContainsKey(node2)) {
                List<int> nodes = new List<int>();
                nodes.Add(node1);
                connections[node2] = nodes;
            }
            else {
                connections[node2].Add(node1);
            }
        }
 
        // Determine the topology based
        // on the connections
        bool isLinear = connections.All(
            nodes = > nodes.Value.Count == 2);
 
        bool isStar = connections.All(
            nodes = > nodes.Value.Count == 1);
 
        bool isRing
            = connections.All(nodes =
                                  > nodes.Value.Count == 2)
              && (edges[0][0] == edges[edges.Count - 1][1]);
 
        string topology
            = isLinear ? "linear"
                       : isStar ? "star"
                                : isRing ? "ring" : "mesh";
 
        // Return the topology
        return topology;
    }
 
    public static void Main()
    {
        // Create a list of edges
        List<List<int> > edges = new List<List<int> >() {
            new List<int>() { 1, 2 },
                new List<int>() { 2, 3 },
                new List<int>() { 3, 4 },
                new List<int>() { 4, 5 },
                new List<int>() { 5, 6 },
                new List<int>() { 6, 1 },
                new List<int>() { 1, 3 },
                new List<int>() { 2, 4 },
                new List<int>() { 3, 5 },
                new List<int>() { 4, 6 }
        };
        Console.WriteLine(findTopology(edges));
    }
}
 
// This code is contributed by shivamsharma215


Output

mesh

Complexity Analysis:

  • The Time Complexity for iterating over the edges and updating the connections dictionary has a linear complexity of O(n), where n is the number of edges. For each edge, the program performs a constant amount of work to update the connections dictionary, so the overall complexity is directly proportional to the number of edges. Overall, the complexity of this pseudocode is O(n), which means it will take longer to run as the number of edges increases. This makes it well-suited for small to medium-sized inputs, but it may not be efficient for very large inputs.
  • The auxiliary space of this code is O(n), where n is the number of edges in the input. The main component of the space complexity is the connections dictionary, which is used to store the connections for each node. The size of this dictionary is directly proportional to the number of edges in the input since each edge corresponds to one entry in the dictionary. The other data structures used in the pseudocode, such as the list of edges and the temporary variables used in the loop, have a constant size and do not contribute significantly to the overall space complexity. Overall, the space complexity of this pseudocode is O(n), which means it will use more memory as the number of edges increases. This may be a concern for very large inputs, but it should not be a problem for most practical applications.


Last Updated : 31 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads