Skip to content

Instantly share code, notes, and snippets.

@abhamra
Created November 12, 2020 00:04
Show Gist options
  • Save abhamra/66c9be9adec8b56c5cdae37779d6f692 to your computer and use it in GitHub Desktop.
Save abhamra/66c9be9adec8b56c5cdae37779d6f692 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
public class Graphs {
int numArrays;
static ArrayList[] arr;
//constructor
public Graphs(int numArrays) {
this.numArrays = numArrays;
arr = new ArrayList[numArrays];
for(int i = 0;i< arr.length;i++) {
arr[i] = new ArrayList<Integer>();
}
}
public static void main(String[]args) {
Graphs g = new Graphs(5);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(2, 4);
for(int i = 0;i<arr.length;i++) {
System.out.println(getEdge(i));
}
}//end main
public void addEdge(int vertex1, int vertex2) {
arr[vertex1].add(vertex2);
arr[vertex2].add(vertex1);
}//end method
public static String getEdge(int vertex) {
String str = vertex + " :";
for(int j = 0;j<arr[vertex].size();j++) {
//System.out.println(vertex+ " : " + arr[vertex].get(j));
str += " " + arr[vertex].get(j);
}
return str;
}//end method
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment