/*
* Demo Vertex class contains only vertexId.
* Can be extended to keep other details.
*/
public class Vertex {
int vertexId;
ArrayList<Edge> edges ;
public Vertex(int id) {
vertexId = id;
edges = new ArrayList<>();
}
public void addEdge(Edge e) {
edges.add(e);
}
}
public class Edge {
Vertex Target;
int weight;
public Edge(Vertex Target, int weight) {
this.Target = Target;
this.weight = weight;
}
}
public class Graph {
/*
* @vertices, ArrayList of all vertices in a graph.
* @directed, boolean variable to store if graph is directed/undirected
* @totalVertices, Total number of vertices in a graph.
*/
Vertex vertices[];
boolean directed;
int totalVertices;
/*
* @param directed , boolean variable to keep if graph is directed.
* @param totalVertices, total number of vertices in a graph.
*/
public Graph(int totalVertices, boolean directed) {
this.totalVertices = totalVertices;
this.directed = directed;
vertices = new Vertex[totalVertices];
for(int i=0; i<totalVertices; i++)
vertices[i] = null;
}
/*
* @param target @param source, check if source and target vertex already present (!=null).
* if source/target vertex not present in graph then create it.
* Else add weighted edge from source to target vertex.
*/
public void addVertex(int source, int target, int weight) {
if(vertices[source] == null) {
vertices[source] = new Vertex(source);
}
if(vertices[target] == null) {
vertices[target] = new Vertex(target);
}
Vertex sourceVertex = vertices[source];
Vertex targetVertex = vertices[target];
sourceVertex.addEdge(new Edge(targetVertex,weight));
if(!directed) {
targetVertex.addEdge(new Edge(sourceVertex,weight));
}
}
}
Friday, 4 October 2013
Adjacency List Implementation
Subscribe to:
Post Comments (Atom)
King Caesar Casino Review 2021 - Shootercasino
ReplyDeleteOur review will 메리트 카지노 주소 describe King Caesar Casino, 인카지노 an 제왕카지노 online casino, poker room, sportsbook, gaming, and more. Claim your bonus now!