Learn-dsa..in 30 days!



























CC-6 : Check if the input graph follows star structure.

Description:

A star graph has a central vertex and all other vertices are connected only to the central vertex. Check if the input graph follows the star structure.

Test cases and expected outputs:

Input Parameters Expected outputs
Adjacency Matrix :
0,1,1,1,
1,0,0,0,
1,0,0,0,
1,0,0,0,
Check Star graph: true
Adjacency Matrix :
0,1,1,1,
1,0,0,0,
1,0,0,0,
0,0,0,0,
Check Star graph: false

Pseudocode:

The adjacencyMatrix of the graph is received as an input parameter.
Using the adjacencyMatrix iterate through all the vertices of the graph and count the number of other vertices it is connected to.
If the following conditions are fulfilled, the graph is a star graph:
Only one node (central node) should be connected to (vertices-1) nodes.
All other nodes should be connected to one node.

Code:

public class GraphCheckStar {
int vertices=0;

public GraphCheckStar(int vertices) {
	 this.vertices=vertices;
}

public boolean checkStarGraph(int[][] matrix){
	int vertexWithDegree1=0;
	int vertexWithDegreeN1=0;
	if (vertices==1)  {return true;}
	if ((vertices==2) && (matrix[0][1]==1) && (matrix[1][0]==1)) {
		return true;
	}
	for (int iIdx=0;iIdx < vertices; iIdx++) {
		int currDegree=0;
		for (int jIdx=0;jIdx < vertices; jIdx++) {
			if (matrix[iIdx][jIdx]==1) {
				currDegree++;
			}
		}
		if (currDegree==1) {vertexWithDegree1++;}
		if (currDegree==vertices-1) {vertexWithDegreeN1++;}
	}
	if ((vertexWithDegree1== vertices-1) && (vertexWithDegreeN1==1)) {
		return true;
	}else {	
		return false;	
	}
}
}

Click here to download and run code and test cases !