Graphs
1.Types
Adjacency matrix
class Graph {
int [][] adjacencyMatrix;
int numVertices;
}
public class AdjacencyMatrixGraph implements Graph {
private int [][] adjacencyMatrix;
private GraphType graphType = GraphType.DIRECTED;
private int numVertices = 0;
public AdjacencyMatrixGraph(int numVertices, GraphType graphType) {
this.numVertices = numVertices;
this.graphType = graphType;
adjacencyMatrix = new int[numVertices][numVertices];
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
adjacencyMatrix[i][j] = 0;
}
}
}
public void addEdge(int v1, int v2) {
if (v1 >= numVertices || V1 < 0 || v2 >= numVertices || v2 < 0) {
throw new IllegalArgumentException("Vertex number is not valid");
}
adjacencyMatrix[v1][v2] = 1;
if (graphType == GraphType.UNDIRECTED) {
adjacencyMatrix[v2][v1] = 1;
}
}
public List<Integar> getAdjacentVertices(int v) {
if (v >= numVertices || v < 0) {
throw new IllegalArgumentException("Vertex number is not valid");
}
List<Integar> adjacencyVerticesList = new ArrayList<>();
for (int i = 0; i < numVertices; i++) {
if (adjacencyMatrix[v][i] == 1) {
adjacencyVerticesList.add(i);
}
}
Collections.sort(adjacencyVerticesList);
return adjacencyVerticesList;
}
}Adjacency list
Adjacency set
2.Compares
3.Traversal
Depth-first traversal (post order)
Breadth-first traversal
Last updated