Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find center of star graph in Python
A star graph is an undirected graph with n nodes where one central node connects to all other n-1 nodes. In this tutorial, we'll learn how to identify the center node of a star graph represented as a list of edges.
Understanding the Problem
Given a star graph with n nodes labeled from 1 to n, we need to find the center node. The center node appears in every edge since it connects to all other nodes.
Algorithm Approach
The key insight is that the center node will appear in multiple edges. We can track which nodes we've seen and return the first node that appears twice ?
Steps:
Create a set to track seen nodes
-
For each edge (u, v) in the graph:
If u is already seen, return u (it's the center)
If v is already seen, return v (it's the center)
Add both u and v to the seen set
Implementation
def find_center(graph):
seen = set()
for u, v in graph:
if u in seen:
return u
if v in seen:
return v
seen.add(u)
seen.add(v)
# Example star graph: edges connecting center node 3 to all others
graph = [(1, 3), (2, 3), (4, 3), (5, 3), (6, 3)]
center = find_center(graph)
print(f"Center of star graph: {center}")
Center of star graph: 3
How It Works
In our example with edges [(1,3), (2,3), (4,3), (5,3), (6,3)]:
Edge (1,3): Add 1 and 3 to seen = {1, 3}
Edge (2,3): Node 3 is already in seen, so return 3
Alternative Approach Using Degree Count
We can also count how many times each node appears ?
def find_center_by_degree(graph):
degree = {}
for u, v in graph:
degree[u] = degree.get(u, 0) + 1
degree[v] = degree.get(v, 0) + 1
# In a star graph, center has degree n-1
if degree[u] > 1:
return u
if degree[v] > 1:
return v
graph = [(1, 3), (2, 3), (4, 3), (5, 3), (6, 3)]
center = find_center_by_degree(graph)
print(f"Center found by degree: {center}")
Center found by degree: 3
Time Complexity
Both approaches have O(1) time complexity for a star graph since we find the center after examining at most 2 edges. The space complexity is also O(1) since we store at most 4 nodes in our tracking structure.
Conclusion
Finding the center of a star graph is efficient using the "seen nodes" approach. The center node appears in multiple edges, making it identifiable after checking just a few edges.
