How would I convert this adjacency matrix into an adjacency list and then print the adjacency list using Java,
How would I convert this adjacency matrix into an adjacency list and then print the adjacency list using Java, I have implemented my own graph data structure and have tried to do this conversion in displayAsList() unsuccessfully.
public class Q5Graph
{
int maxsize;
int wmatrix[][];
String labels[];
int vertexCount;
public Q5Graph()
{
maxsize = 20;
wmatrix = new int[maxsize][maxsize];
labels = new String[maxsize];
for(int i=0; i < maxsize; i++)
for (int j=0; j< maxsize; j++)
{
wmatrix[i][j] = 0;
}
vertexCount = 0;
}
public void addVertex(String label)
{
if (vertexCount == maxsize)
{
throw new IllegalArgumentException("Graph is already full!");
}
else if (hasVertex(label))
{
throw new IllegalArgumentException("Vertex '"+label+"' already exists");
}
else
{
labels[vertexCount] = label;
vertexCount++;
}
}
public void addEdge(String label1, String label2, int weight)
{
int v1, v2;
if(!hasVertex(label1)){
throw new IllegalArgumentException("First Vertex '" + label1 + "' does not exist yet!");
}
else if(!hasVertex(label2)){
throw new IllegalArgumentException("Second Vertex '" + label2 + "' does not exist yet!");
}
else
{
v1 = getIndex(label1);
v2 = getIndex(label2);
wmatrix[v1][v2] = weight;
}
}
public boolean hasVertex(String label)
{
boolean has = false;
for (int i=0; i < vertexCount; i++)
{
if (labels[i].equals(label))
has = true;
}
return has;
}
public int getIndex(String label)
{
int theVertex = -1;
for (int i=0; i < vertexCount; i++)
{
if (labels[i].equals(label))
theVertex = i;
}
return theVertex;
}
public int[][] getMatrix()
{
return wmatrix;
}
public String[] getLabels()
{
return labels;
}
public void displayAsList(int[][] wmatrix, String[] labels) //This is what i have tried
{
int l = wmatrix[0].length;
String[] adjList = new String[l];
//for(int i = 0; i < l; i++)
//{
// adjList[i] = new String[l];
//}
int i, j;
for(i = 0; i < labels.length; i++)
{
for(j = 0; j < wmatrix.length; j++)
{
adjList[i] = labels[i];
if(wmatrix[i][j] != 0)
{
adjList[i] = adjList[i]+" -> "+labels[j];
}
}
}
System.out.println("Adjacency List display (stub)");
for(int v = 0; v < adjList.length; v++)
{
//System.out.print(v);
for(String u : adjList)
{
if(u != null)
{
System.out.print(u);
}
}
System.out.println();
}
}
Step by step
Solved in 3 steps