0% found this document useful (0 votes)
8 views

Graphs

The document provides an overview of graph representation in Java, including various methods for representing vertices and edges such as edge arrays, edge objects, adjacency matrices, and adjacency lists. It also discusses graph traversal techniques like depth-first search (DFS) and breadth-first search (BFS), along with the implementation of search trees. Additionally, it covers the representation of weighted edges and the creation of weighted graphs.

Uploaded by

poojamp450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Graphs

The document provides an overview of graph representation in Java, including various methods for representing vertices and edges such as edge arrays, edge objects, adjacency matrices, and adjacency lists. It also discusses graph traversal techniques like depth-first search (DFS) and breadth-first search (BFS), along with the implementation of search trees. Additionally, it covers the representation of weighted edges and the creation of weighted graphs.

Uploaded by

poojamp450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Graphs in Java

Modeling Using Graphs


Representing Graphs
Representing Vertices
Representing Edges: Edge Array
Representing Edges: Edge Objects
Representing Edges: Adjacency Matrices
Representing Edges: Adjacency Lists
Representing Vertices
String[] vertices = {“Seattle“, “San
Francisco“, “Los Angles”, “Denver”, “Kansas
City”, “Chicago”, … };

City[] vertices = {city0, city1, … };

public class City {

List<String> vertices;
Representing Edges: Edge Array
int[ ][ ] edges = {
{0, 1}, {0, 3} {0, 5}, {1, 0}, {1, 2},

};
Representing Edges: Edge Object
Edge.java
public class Edge {
int u;
int v;
public Edge(int u, int v) {
this.u = u;
this.v = v;}
public boolean equals(Object o) {
return u == ((Edge)o).u && v == ((Edge)o).v;
}}
For example:
ArrayList<Edge> list = new ArrayList<>();
list.add(new Edge(0, 1));
list.add(new Edge(0, 3));
list.add(new Edge(0, 5));
Representing Edges: Adjacency Matrix
int[][] adjacencyMatrix = {
{0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0}, // Seattle
{1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, // San Francisco
{0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}, // Los Angeles
{1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0}, // Denver
{0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0}, // Kansas City
{1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0}, // Chicago
{0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, // Boston
{0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0}, // New York
{0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1}, // Atlanta
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1}, // Miami
{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1}, // Dallas
{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0} // Houston
};
Representing Edges: Adjacency Vertex List
List<Integer>[] neighbors = new List[12];

List<List<Integer>> neighbors = new ArrayList<>();


Representing Edges: Adjacency Edge List
List<Edge>[] neighbors = new List[12];
Representing Adjacency Edge List Using
ArrayList
List<ArrayList<Edge>> neighbors = new ArrayList<>();
neighbors.add(new ArrayList<Edge>());
neighbors.get(0).add(new Edge(0, 1));
neighbors.get(0).add(new Edge(0, 3));
neighbors.get(0).add(new Edge(0, 5));
neighbors.add(new ArrayList<Edge>());
neighbors.get(1).add(new Edge(1, 0));
neighbors.get(1).add(new Edge(1, 2));
neighbors.get(1).add(new Edge(1, 3));
...
...
neighbors.get(11).add(new Edge(11, 8));
neighbors.get(11).add(new Edge(11, 9));
neighbors.get(11).add(new Edge(11, 10));
List<V> vertices = new ArrayList<>();

//Adjacency Edge lists


List<List<Edge>> neighbors = new ArrayList<>();

public V getVertex(int index) {


return vertices.get(index);
}
Adjacency List
private void
createAdjacencyLists(int[][] edges, int numberOfVertices)
{
for (int i = 0; i < edges.length; i++) {
addEdge(edges[i][0], edges[i][1]);
}
}
/** Create adjacency lists for each vertex */
private void
createAdjacencyLists(List<Edge> edges, int numberOfVertices)
{
for (Edge edge: edges) {
addEdge(edge.u, edge.v);
}
}
public void printEdges() {
for (int u = 0; u < neighbors.size(); u++) {
System.out.print(getVertex(u) + " (" + u + "): ");
for (Edge e: neighbors.get(u)) {
System.out.print("(" + getVertex(e.u) + ", " +
getVertex(e.v) + ") ");
}
System.out.println();
}
}
Graph: TestGraph.java
public class TestGraph {
public static void main(String[ ] args) {
String[ ] vertices = {"Seattle", "San Francisco", "Los Angeles",
"Denver", "Kansas City", "Chicago", "Boston", "New York",
"Atlanta", "Miami", "Dallas", "Houston"};
int[ ][ ] edges = { {0, 1}, {0, 3}, {0, 5}, {1, 0}, {1, 2}, {1, 3},
{2, 1}, {2, 3}, {2, 4}, {2, 10}, {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5},
{4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10},
{5, 0}, {5, 3}, {5, 4}, {5, 6}, {5, 7},
{6, 5}, {6, 7}, {7, 4}, {7, 5}, {7, 6}, {7, 8},
{8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11}, {9, 8}, {9, 11},
{10, 2}, {10, 4}, {10, 8}, {10, 11},
{11, 8}, {11, 9}, {11, 10}
};
Graph<String> graph1 = new UnweightedGraph<>(vertices, edges);
System.out.println("The number of vertices in
graph1: " + graph1.getSize());
System.out.println("The vertex with index 1 is
" + graph1.getVertex(1));
System.out.println("The index for Miami is " +
graph1.getIndex("Miami"));
System.out.println("The edges for graph1:");
graph1.printEdges();
String[] names = {"Peter", "Jane", "Mark", "Cindy",
"Wendy"};
java.util.ArrayList<Edge> edgeList = new
java.util.ArrayList<>();
edgeList.add(new Edge(0, 2));
edgeList.add(new Edge(1, 2));
edgeList.add(new Edge(2, 4));
edgeList.add(new Edge(3, 4));
// Create a graph with 5 vertices
Graph<String> graph2 = new UnweightedGraph<>
(java.util.Arrays.asList(names), edgeList);
System.out.println(“Number of vertices in graph2:“
+ graph2.getSize());
System.out.println("The edges for graph2:");
graph2.printEdges();
} }
Graph Traversals
• Depth-first search and breadth-first search
• Both traversals result in a spanning tree, which can
be modeled using a class.
Search Tree Inner Class
• SearchTree class defines seven methods.
• getRoot() method returns the root of the tree.
• Get the order of the vertices searched by invoking the
getSearchOrder() method.
• Invoke getParent(v) to find the parent of vertex v in the
search.
• Invoking getNumberOfVerticesFound() returns the number
of vertices searched.
• Method getPath(index)returns a list of vertices from the
specified vertex index to the root.
• printPath(v) displays a path from the root to v.
• printTree() method displays all edges in the tree.
public class SearchTree {
private int root; // The root of the tree
private int[ ] parent; // Store the parent of each vertex
private List<Integer> searchOrder; // Store the search order

/** Construct a tree with root, parent, and searchOrder */


public SearchTree(int root, int[] parent,
List<Integer> searchOrder) {
this.root = root;
this.parent = parent;
this.searchOrder = searchOrder;
}

/** Return the root of the tree */


public int getRoot() {
return root;
/** Return an array representing search order */
public List<Integer> getSearchOrder() {
return searchOrder;
}
/** Return number of vertices found */
public int getNumberOfVerticesFound() {
return searchOrder.size();
}
/** Return the path of vertices from a vertex to the root */
public List<V> getPath(int index) {
ArrayList<V> path = new ArrayList<>();
do {
path.add(vertices.get(index));
index = parent[index]; }
while (index != −1);
/** Print a path from the root to vertex v */
public void printPath(int index) {
List<V> path = getPath(index);
System.out.print("A path from " + vertices.get(root) + " to " +
vertices.get(index) + ": ");
for (int i = path.size() − 1; i >= 0; i−−)
System.out.print(path.get(i) + " ");
}

/** Print the whole tree */


public void printTree() {
System.out.println("Root is: " + vertices.get(root));
System.out.print("Edges: ");
What will be the output here?
public class Test {
public static void main(String[] args) {
Graph<Character> graph = new UnweightedGraph<>();
graph.addVertex('U');
graph.addVertex('V');
int indexForU = graph.getIndex('U');
int indexForV = graph.getIndex('V');
System.out.println("indexForU is " + indexForU);
System.out.println("indexForV is " + indexForV);
graph.addEdge(indexForU, indexForV);
System.out.println("Degree of U is " +
graph.getDegree(indexForU));
System.out.println("Degree of V is " +
graph.getDegree(indexForV));
}
}
Depth-First Search
• In the case of a tree, the search starts from the root.
• In a graph, the search can start from any vertex.
• Input: G = (V, E) and a starting
vertex v
• Output: a DFS tree rooted at v
Tree dfs(vertex v) {
visit v;
for each neighbor w of v
if (w has not been visited) {
set v as the parent for w;
dfs(w);
}
}
Depth-First Search Example
DFS
String[] vertices = {"Seattle", "San
Francisco", "Los Angeles", "Denver",
"Kansas City", "Chicago", "Boston",
"New York", "Atlanta", "Miami",
"Dallas", "Houston"};
int[][] edges = { {0, 1}, {0, 3}, {0, 5},
{1, 0}, {1, 2}, {1, 3}, {2, 1}, {2, 3},
{2, 4}, {2, 10}, {3, 0}, {3, 1}, {3,
2}, {3, 4}, {3, 5}, {4, 2}, {4, 3}, {4,
5}, {4, 7}, {4, 8}, {4, 10}, {5, 0},
{5, 3}, {5, 4}, {5, 6}, {5, 7}, {6, 5},
{6, 7}, {7, 4}, {7, 5}, {7, 6}, {7, 8},
{8, 4}, {8, 7}, {8, 9}, {8, 10}, {8,
11}, {9, 8}, {9, 11}, {10, 2}, {10, 4},
{10, 8},
{10, 11}, {11, 8}, {11, 9}, {11, 10} };
Graph<String> graph = new
UnweightedGraph<>(vertices, edges);
UnweightedGraph<String>.SearchTree dfs =
graph.dfs(graph.getIndex("Chicago"));
// Get a dfs starting at Chicago
java.util.List<Integer> searchOrders =
dfs.getSearchOrder();
System.out.println(dfs.getNumberOfVerticesFound
() + " vertices are searched in DFS order:");
for (int i = 0; i < searchOrders.size(); i++)
System.out.print(
graph.getVertex(searchOrders.get(i));
System.out.println();
for (int i = 0; i < searchOrders.size(); i++)
if (dfs.getParent(i) != -1)
System.out.println("parent of " +
graph.getVertex(i) + " is " +
graph.getVertex(dfs.getParent(i)));
Breadth-First Search Algorithm
Input: G = (V, E) and a starting vertex v
Output: a BFS tree rooted at v
bfs(vertex v) {
create an empty queue for storing vertices to be visited;
add v into the queue;
mark v visited;
while the queue is not empty {
dequeue a vertex, u, from the queue
process u;
for each neighbor w of u
if w has not been visited {
add w into the queue;
set u as the parent for w;
mark w visited;
}}}
Breadth-First Search Example

Queue: 0 isVisited[0] = true

Queue: 1 2 3 isVisited[1] = true, isVisited[2] = true, isVisited[3] = true

Queue: 2 3 4 isVisited[4] = true


Representing Weighted Edges: Edge Array
Object[][] edges = {
{new Integer(0), new Integer(1), new
SomeTypeForWeight(2)},
{new Integer(0), new Integer(3), new
SomeTypeForWeight(8)},
...
};
Integer[][] adjacencyMatrix = {
{null, 2, null, 8, null},
{2, null, 7, 3, null},
{null, 7, null, 4, 5},
{8, 3, 4, null, 6},
{null, null, 5, 6, null}
};
Adjacency Lists
public class WeightedEdge extends Edge
implements Comparable<WeightedEdge> {
public double weight; // The weight on edge (u, v)
/** Create a weighted edge on (u, v) */
public WeightedEdge(int u, int v, double weight) {
super(u, v);
this.weight = weight;}

@Override /** Compare two edges on weights */


public int compareTo(WeightedEdge edge) {
if (weight > edge.weight)
return 1;
else if (weight == edge.weight)
return 0;
else
return −1; }
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy