VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-star-graph/

⇱ Check for star graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for star graph

Last Updated : 21 Mar, 2023

You are given an n * n matrix which represents a graph with n-vertices, check whether the input matrix represents a star graph or not.

Example: 

Input : Mat[][] = {{0, 1, 0},
 {1, 0, 1},
 {0, 1, 0}}
Output : Star graph

Input : Mat[][] = {{0, 1, 0},
 {1, 1, 1},
 {0, 1, 0}}
Output : Not a Star graph


Star graph: Star graph is a special type of graph in which n-1 vertices have degree 1 and a single vertex have degree n - 1. This looks like n - 1 vertex is connected to a single central vertex. A star graph with total n - vertex is termed as Sn.
Here is an illustration for the star graph : 
 

👁 Check for star graph


Approach: Just traverse whole matrix and record the number of vertices having degree 1 and degree n-1. If number of vertices having degree 1 is n-1 and number of vertex having degree n-1 is 1 then our graph should be a star graph other-wise it should be not. 

Note:

  • For S1, there must be only one vertex with no edges.
  • For S2, there must be two vertices each with degree one or can say, both are connected by a single edge.
  • For Sn (n>2) simply check the above-explained criteria.

Implementation:


Output
Star Graph

Approach 2: Breath First Search:

The BFS approach of the code first initializes an integer array 'degree' of size 'size' to store the degree of each vertex in the graph. It then traverses the graph using two nested loops and calculates the degree of each vertex by counting the number of edges that are incident on the vertex. The degree of each vertex is stored in the corresponding position of the 'degree' array.

Next, the code searches for a center vertex of the graph. A center vertex is a vertex that is connected to all other vertices in the graph. The code checks the degree of each vertex in the 'degree' array and looks for a vertex whose degree is equal to the size of the graph minus one. If such a vertex is found, it is stored in the 'center' variable.


Output
Star Graph

Time Complexity: O(size^2), where size is the size of the adjacency matrix. 
Auxiliary Space: O(size), where size is the size of the adjacency matrix.

Comment
Article Tags:
Article Tags: