23. Consider the following class definition for anundirected graph. public class
ID: 3612504 • Letter: 2
Question
23. Consider the following class definition for anundirected graph.
public class graph
{
public graph(int n)
//initializes the number of vertices to n, and fills//matrix with zeros
public void addEdge(int v, intw)
//add an edge between v and w
public int printAdjacent(intv)
//print all vertices that are adjacent to v
public void printMatrix()
/* print the content of the adjacency matrix
with one row per line ofoutput*/
private intmatrix[][];
private int vertices; //numberof vertices
}
Explanation / Answer
publicgraph(int n)
{
vertices=n;
matrix = new int[n][n];
}
//initializes the number of vertices to n, and fills //matrix withzeros
publicvoid addEdge(int v, int w){
matrix[v][w]=1;
}
//add an edge between vand w
publicint printAdjacent(int v)
{
int i;
for(i=0;i<vertices;i++)
if(matrix[v][i]==1)
System.out.println(i);
return 1;
}
//print all vertices that are adjacent to v
public voidprintMatrix()
{
int i,j;
for(i=0;i<vertices;i++)
for(j=0;j<vertices;j++)
{
if(j==0)
System.out.println();
System.out.print(matrix[i][j]+ " " );
}
}
/*print the content of the adjacency matrix
with one rowper line of output*/
private int matrix[][];
private int vertices; //number of vertices
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.