SlideShare a Scribd company logo
Write a program that reads a graph from a file and determines
whether the graph is connected. The first line in the file
contains a number that indicates the number of vertices (n). The
vertices are labeled as 0, 1,..., n-1. Each subsequent line, with
the format u v1 v2..., describes edges (u, v1), (u, v2), and so on.
Figure gives the examples of two files for their corresponding
graphs. Your program should prompt the user to enter the name
of the file, then it should read data from the file, create an
instance g of UnweightedGraph, invoke g.printEdges() to
display all edges, and invoke dfs() to obtain an instance tree of
AbstractGraph.Tree. If tree.getNumberOfVerticesFound() is the
same as the number of vertices in the graph, the graph is
connected. Here is a sample run of the program:
Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// class to test the graph is connected or not
public class Exercise28_01 {
// main method
public static void main(String[] exargs) throws
FileNotFoundException
{
// get the file name
System.out.print("Enter a file name: ");
@SuppressWarnings("resource")
// create a object for scanner class and declare the required
variables
Scanner inFileName = new Scanner(System.in);
String fileNm = inFileName.nextLine();
Scanner Grpinp = new Scanner(new File(fileNm));
int Verticesnum = Grpinp.nextInt();
Grpinp.nextLine();
//proces the data
System.out.println("The number of vertices is " +
Verticesnum);
ArrayList<Integer> lstvertices = new ArrayList();
ArrayList<AbstractGraph.Edge> lstedge = new
ArrayList();
for (int lp = 0; lp < Verticesnum; lp++) {
Scanner inpVert = new Scanner(Grpinp.nextLine());
int vrtx = inpVert.nextInt();
lstvertices.add(vrtx);
while(inpVert.hasNext()) {
lstedge.add(new AbstractGraph.Edge(vrtx,
inpVert.nextInt()));
}
inpVert.close();
}
Grpinp.close();
UnweightedGraph<Integer> unWgtgraph = new
UnweightedGraph(lstedge, lstvertices);
unWgtgraph.printEdges();
// validate and print the message
if(unWgtgraph.dfs(0).getNumberOfVerticesFound() ==
Verticesnum)
{
System.out.print("The graph is connected");
} else {
System.out.print("The graph is not connected");
}
}
// class for unweighted graph
static class UnweightedGraph<G> extends AbstractGraph<G>
{
//constructor
public UnweightedGraph() {}
//constructor
public UnweightedGraph(int[][] lstedge, G[] lstvertices)
{
super(lstedge, lstvertices);
}
//constructor
public UnweightedGraph(List<Edge> lstedge, List<G>
lstvertices)
{
super(lstedge, lstvertices);
}
//constructor
public UnweightedGraph(List<Edge> lstedge, int
Verticesnum)
{
super(lstedge, Verticesnum);
}
//constructor
public UnweightedGraph(int[][] lstedge, int Verticesnum)
{
super(lstedge, Verticesnum);
}
}
// class for abstact graph
static abstract class AbstractGraph<G> implements
Graph<G>
{
protected List<G> lstvertices = new ArrayList<G>();
protected List<List<Integer>> lstneighbors = new
ArrayList<List<Integer>>();
//constructor
protected AbstractGraph() {}
//constructor
protected AbstractGraph(int[][] lstedge, G[] lstvertices)
{
for (int lp = 0; lp < lstvertices.length; lp++)
this.lstvertices.add(lstvertices[lp]);
createAdjacencyLists(lstedge, lstvertices.length);
}
//constructor
protected AbstractGraph(List<Edge> lstedge, List<G>
lstvertices)
{
for (int lp = 0; lp < lstvertices.size(); lp++)
this.lstvertices.add(lstvertices.get(lp));
createAdjacencyLists(lstedge, lstvertices.size());
}
//constructor
@SuppressWarnings("unchecked")
protected AbstractGraph(List<Edge> lstedge, int
Verticesnum)
{
for (int lp = 0; lp < Verticesnum; lp++)
lstvertices.add((G) (new Integer(lp))); // vertices is
{0, 1, ...}
createAdjacencyLists(lstedge, Verticesnum);
}
//constructor
@SuppressWarnings("unchecked")
protected AbstractGraph(int[][] lstedge, int Verticesnum)
{
for (int lp = 0; lp < Verticesnum; lp++)
lstvertices.add((G) (new Integer(lp)));
createAdjacencyLists(lstedge, Verticesnum);
}
// method to cretae a adjacency lists
private void createAdjacencyLists(int[][] lstedge, int
Verticesnum)
{
// code for linked list
for (int lp = 0; lp < Verticesnum; lp++)
{
lstneighbors.add(new ArrayList<Integer>());
}
for (int lp = 0; lp < lstedge.length; lp++)
{
int utx = lstedge[lp][0];
int vrtx = lstedge[lp][1];
lstneighbors.get(utx).add(vrtx);
}
}
// method for adjacency lists
private void createAdjacencyLists(List<Edge> lstedge, int
Verticesnum)
{
// code for linked list
for (int lp = 0; lp < Verticesnum; lp++)
{
lstneighbors.add(new ArrayList<Integer>());
}
for (Edge edge : lstedge)
{
lstneighbors.get(edge.utx).add(edge.vrtx);
}
}
// method to return the number of vertices
public int getSize()
{
return lstvertices.size();
}
//method to return the vertices
public List<G> getVertices()
{
return lstvertices;
}
//method to return the specific vertex
public G getVertex(int index)
{
return lstvertices.get(index);
}
//method to return the index of specific vertex
public int getIndex(G g)
{
return lstvertices.indexOf(g);
}
//method to return the neighbour of specific vertex
public List<Integer> getNeighbors(int index)
{
return lstneighbors.get(index);
}
//method to return the degree of specific vertex
public int getDegree(int vrtx)
{
return lstneighbors.get(vrtx).size();
}
//method to print the edges
public void printEdges()
{
for (int utx = 0; utx < lstneighbors.size(); utx++)
{
System.out.print(getVertex(utx) + " (" + utx + "):
");
for (int j = 0; j < lstneighbors.get(utx).size(); j++)
{
System.out.print("(" + utx + ", " +
lstneighbors.get(utx).get(j)
+ ") ");
}
System.out.println();
}
}
// method to clear the graph
public void clear()
{
lstvertices.clear();
lstneighbors.clear();
}
// method to add the vertex to graph
public void addVertex(G g)
{
lstvertices.add(g);
lstneighbors.add(new ArrayList<Integer>());
}
// method to add an edge to the graph
public void addEdge(int utx, int vrtx)
{
lstneighbors.get(utx).add(vrtx);
lstneighbors.get(vrtx).add(utx);
}
//class edge
public static class Edge
{
public int utx;
public int vrtx;
// constructor
public Edge(int utx, int vrtx)
{
this.utx = utx;
this.vrtx = vrtx;
}
}
// dfs tree
public Tree dfs(int vrtx)
{
List<Integer> ordrSearch = new ArrayList<Integer>();
int[] parnt = new int[lstvertices.size()];
for (int lp = 0; lp < parnt.length; lp++)
parnt[lp] = -1;
boolean[] isVst = new boolean[lstvertices.size()];
// Recursively search
dfs(vrtx, parnt, ordrSearch, isVst);
// Return a search tree
return new Tree(vrtx, parnt, ordrSearch);
}
//method for the DFS search
private void dfs(int vrtx, int[] parnt, List<Integer>
ordrSearch,
boolean[] isVst)
{
ordrSearch.add(vrtx);
isVst[vrtx] = true;
for (int lp : lstneighbors.get(vrtx))
{
if (!isVst[lp])
{
parnt[lp] = vrtx;
dfs(lp, parnt, ordrSearch, isVst);
}
}
}
// code for bfs
public Tree bfs(int vrtx)
{
List<Integer> ordrSearch = new ArrayList<Integer>();
int[] parnt = new int[lstvertices.size()];
for (int lp = 0; lp < parnt.length; lp++)
parnt[lp] = -1;
java.util.LinkedList<Integer> queue = new
java.util.LinkedList<Integer>();
boolean[] isVst = new boolean[lstvertices.size()];
queue.offer(vrtx);
isVst[vrtx] = true;
while (!queue.isEmpty())
{
int utx = queue.poll();
ordrSearch.add(utx);
for (int w : lstneighbors.get(utx))
{
if (!isVst[w])
{
queue.offer(w);
parnt[w] = utx;
isVst[w] = true;
}
}
}
return new Tree(vrtx, parnt, ordrSearch);
}
//class tree
public class Tree
{
private int root;
private int[] parnt;
private List<Integer> ordrSearch;
// Code for tree construction
public Tree(int root, int[] parnt, List<Integer>
ordrSearch) {
this.root = root;
this.parnt = parnt;
this.ordrSearch = ordrSearch;
}
// method to return tree root
public int getRoot() {
return root;
}
// method to return parent
public int getParent(int vrtx) {
return parnt[vrtx];
}
// // method to return search order
public List<Integer> getSearchOrder()
{
return ordrSearch;
}
// method to return number of vertices
public int getNumberOfVerticesFound()
{
return ordrSearch.size();
}
// method to return vertices path
public List<G> getPath(int index)
{
ArrayList<G> path = new ArrayList<G>();
do {
path.add(lstvertices.get(index));
index = parnt[index];
} while (index != -1);
return path;
}
// // method to pritn the path
public void printPath(int index) {
List<G> path = getPath(index);
System.out.print("A path from " +
lstvertices.get(root) + " to "
+ lstvertices.get(index) + ": ");
for (int lp = path.size() - 1; lp >= 0; lp--)
System.out.print(path.get(lp) + " ");
}
// method to print whole tree
public void printTree()
{
System.out.println("Root is: " +
lstvertices.get(root));
System.out.print("Edges: ");
for (int lp = 0; lp < parnt.length; lp++)
{
if (parnt[lp] != -1)
{
// Display an edge
System.out.print("(" +
lstvertices.get(parnt[lp]) + ", "
+ lstvertices.get(lp) + ") ");
}
}
System.out.println();
}
}
}
// Graph interface
interface Graph<G> {
// to get the number of vertices
public int getSize();
// to get the vertices
public java.util.List<G> getVertices();
// to get the object
public G getVertex(int index);
// to get index
public int getIndex(G g);
// to get neighbours
public java.util.List<Integer> getNeighbors(int index);
// // to get the degree
public int getDegree(int vrtx);
// to print the edges
public void printEdges();
// to clear the graph
public void clear();
// to add the vertex into the graph
public void addVertex(G g);
// to add edge in the graph
public void addEdge(int utx, int vrtx);
// to perform dfs
public AbstractGraph<G>.Tree dfs(int vrtx);
// to perform bfs
public AbstractGraph<G>.Tree bfs(int vrtx);
}
}
Result:
Enter a file name: data1.txt
The number of vertices is 6
0 (0): (0, 1) (0, 2)
1 (1): (1, 0) (1, 3)
2 (2): (2, 0) (2, 3) (2, 4)
3 (3): (3, 1) (3, 2) (3, 4) (3, 5)
4 (4): (4, 2) (4, 3) (4, 5)
5 (5): (5, 3) (5, 4)
The graph is connected

More Related Content

DOCX
Write a program that reads a graph from a file anil determines whethe.docx
PDF
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
PDF
CS253: Minimum spanning Trees (2019)
PDF
Complete the implementation of the Weighted Graph that we began in t.pdf
DOCX
2Part I1. Answer questions for the following graph, if .docx
PPTX
Unit 4 dsuc
PPTX
Graph Representation, DFS and BFS Presentation.pptx
DOCX
Write a program that reads a connected graph from a file and displays.docx
Write a program that reads a graph from a file anil determines whethe.docx
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
CS253: Minimum spanning Trees (2019)
Complete the implementation of the Weighted Graph that we began in t.pdf
2Part I1. Answer questions for the following graph, if .docx
Unit 4 dsuc
Graph Representation, DFS and BFS Presentation.pptx
Write a program that reads a connected graph from a file and displays.docx

Similar to Write a program that reads a graph from a file and determines whether.docx (20)

PDF
PPTX
130210107039 2130702
PPT
Graphs concept in data structures and algorithms.ppt
PPSX
Unit-6 Graph.ppsx ppt
PPTX
PPTX
DATA STRUCTURES.pptx
PPT
Prim's Algorithm on minimum spanning tree
PPT
graph4Its about graph topic in data structure.ppt
PPTX
Lecture 16 data structures and algorithms
DOCX
6Modify the bfs.java program (Listing A) to find the minimu.docx
PPTX
8150.graphs
PPT
Graphs.ppt of mathemaics we have to clar all doubts
PPT
Graphs.ppt
PPTX
Graph Data Structure
PPTX
Basic Graph Algorithms Vertex (Node): lk
PPT
Data Structures-Non Linear DataStructures-Graphs
PPTX
Graph Algorithms
PPT
14. GRAPH in data structures and algorithm.ppt
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
130210107039 2130702
Graphs concept in data structures and algorithms.ppt
Unit-6 Graph.ppsx ppt
DATA STRUCTURES.pptx
Prim's Algorithm on minimum spanning tree
graph4Its about graph topic in data structure.ppt
Lecture 16 data structures and algorithms
6Modify the bfs.java program (Listing A) to find the minimu.docx
8150.graphs
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt
Graph Data Structure
Basic Graph Algorithms Vertex (Node): lk
Data Structures-Non Linear DataStructures-Graphs
Graph Algorithms
14. GRAPH in data structures and algorithm.ppt
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Ad

More from ajoy21 (20)

DOCX
Please complete the assignment listed below.Define and explain, us.docx
DOCX
Please cite sources for each question. Do not use the same sources f.docx
DOCX
Please choose one of the following questions to answer for this week.docx
DOCX
Please check the attachment for my paper.Please add citations to a.docx
DOCX
Please answer to this discussion post. No less than 150 words. Refer.docx
DOCX
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
DOCX
Please answer the question .There is no work count. PLEASE NUMBER .docx
DOCX
Please answer the following questions. Please cite your references..docx
DOCX
Please answer the following questions.1.      1.  Are you or.docx
DOCX
Please answer the following question with 200-300 words.Q. Discu.docx
DOCX
Please answer the following question Why do you think the US ha.docx
DOCX
Please answer the following questions. Define tunneling in the V.docx
DOCX
Please answer the following questions1. How can you stimulate the.docx
DOCX
Please answer the following questions very deeply and presicely .docx
DOCX
Please answer the following questions in an informal 1 ½ - 2-page es.docx
DOCX
Please answer the following questions in a response of 150 to 200 wo.docx
DOCX
Please answer these questions regarding the (TILA) Truth in Lending .docx
DOCX
Please answer the following question pertaining to psychology. Inc.docx
DOCX
Please answer the following questions in a response of 250 to 300 .docx
DOCX
Please answer the three questions completly. I have attached the que.docx
Please complete the assignment listed below.Define and explain, us.docx
Please cite sources for each question. Do not use the same sources f.docx
Please choose one of the following questions to answer for this week.docx
Please check the attachment for my paper.Please add citations to a.docx
Please answer to this discussion post. No less than 150 words. Refer.docx
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
Please answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the following questions. Please cite your references..docx
Please answer the following questions.1.      1.  Are you or.docx
Please answer the following question with 200-300 words.Q. Discu.docx
Please answer the following question Why do you think the US ha.docx
Please answer the following questions. Define tunneling in the V.docx
Please answer the following questions1. How can you stimulate the.docx
Please answer the following questions very deeply and presicely .docx
Please answer the following questions in an informal 1 ½ - 2-page es.docx
Please answer the following questions in a response of 150 to 200 wo.docx
Please answer these questions regarding the (TILA) Truth in Lending .docx
Please answer the following question pertaining to psychology. Inc.docx
Please answer the following questions in a response of 250 to 300 .docx
Please answer the three questions completly. I have attached the que.docx
Ad

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Onica Farming 24rsclub profitable farm business
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Structure & Organelles in detailed.
PPTX
Pharma ospi slides which help in ospi learning
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Business Ethics Teaching Materials for college
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Onica Farming 24rsclub profitable farm business
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Structure & Organelles in detailed.
Pharma ospi slides which help in ospi learning
Basic Mud Logging Guide for educational purpose
Week 4 Term 3 Study Techniques revisited.pptx
Microbial diseases, their pathogenesis and prophylaxis
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Business Ethics Teaching Materials for college
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

Write a program that reads a graph from a file and determines whether.docx

  • 1. Write a program that reads a graph from a file and determines whether the graph is connected. The first line in the file contains a number that indicates the number of vertices (n). The vertices are labeled as 0, 1,..., n-1. Each subsequent line, with the format u v1 v2..., describes edges (u, v1), (u, v2), and so on. Figure gives the examples of two files for their corresponding graphs. Your program should prompt the user to enter the name of the file, then it should read data from the file, create an instance g of UnweightedGraph, invoke g.printEdges() to display all edges, and invoke dfs() to obtain an instance tree of AbstractGraph.Tree. If tree.getNumberOfVerticesFound() is the same as the number of vertices in the graph, the graph is connected. Here is a sample run of the program: Solution import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // class to test the graph is connected or not public class Exercise28_01 { // main method public static void main(String[] exargs) throws FileNotFoundException
  • 2. { // get the file name System.out.print("Enter a file name: "); @SuppressWarnings("resource") // create a object for scanner class and declare the required variables Scanner inFileName = new Scanner(System.in); String fileNm = inFileName.nextLine(); Scanner Grpinp = new Scanner(new File(fileNm)); int Verticesnum = Grpinp.nextInt(); Grpinp.nextLine(); //proces the data System.out.println("The number of vertices is " + Verticesnum); ArrayList<Integer> lstvertices = new ArrayList(); ArrayList<AbstractGraph.Edge> lstedge = new ArrayList(); for (int lp = 0; lp < Verticesnum; lp++) { Scanner inpVert = new Scanner(Grpinp.nextLine()); int vrtx = inpVert.nextInt(); lstvertices.add(vrtx); while(inpVert.hasNext()) { lstedge.add(new AbstractGraph.Edge(vrtx, inpVert.nextInt())); }
  • 3. inpVert.close(); } Grpinp.close(); UnweightedGraph<Integer> unWgtgraph = new UnweightedGraph(lstedge, lstvertices); unWgtgraph.printEdges(); // validate and print the message if(unWgtgraph.dfs(0).getNumberOfVerticesFound() == Verticesnum) { System.out.print("The graph is connected"); } else { System.out.print("The graph is not connected"); } } // class for unweighted graph static class UnweightedGraph<G> extends AbstractGraph<G> { //constructor public UnweightedGraph() {} //constructor public UnweightedGraph(int[][] lstedge, G[] lstvertices) { super(lstedge, lstvertices);
  • 4. } //constructor public UnweightedGraph(List<Edge> lstedge, List<G> lstvertices) { super(lstedge, lstvertices); } //constructor public UnweightedGraph(List<Edge> lstedge, int Verticesnum) { super(lstedge, Verticesnum); } //constructor public UnweightedGraph(int[][] lstedge, int Verticesnum) { super(lstedge, Verticesnum); } } // class for abstact graph static abstract class AbstractGraph<G> implements Graph<G> { protected List<G> lstvertices = new ArrayList<G>(); protected List<List<Integer>> lstneighbors = new
  • 5. ArrayList<List<Integer>>(); //constructor protected AbstractGraph() {} //constructor protected AbstractGraph(int[][] lstedge, G[] lstvertices) { for (int lp = 0; lp < lstvertices.length; lp++) this.lstvertices.add(lstvertices[lp]); createAdjacencyLists(lstedge, lstvertices.length); } //constructor protected AbstractGraph(List<Edge> lstedge, List<G> lstvertices) { for (int lp = 0; lp < lstvertices.size(); lp++) this.lstvertices.add(lstvertices.get(lp)); createAdjacencyLists(lstedge, lstvertices.size()); } //constructor @SuppressWarnings("unchecked") protected AbstractGraph(List<Edge> lstedge, int Verticesnum) { for (int lp = 0; lp < Verticesnum; lp++) lstvertices.add((G) (new Integer(lp))); // vertices is
  • 6. {0, 1, ...} createAdjacencyLists(lstedge, Verticesnum); } //constructor @SuppressWarnings("unchecked") protected AbstractGraph(int[][] lstedge, int Verticesnum) { for (int lp = 0; lp < Verticesnum; lp++) lstvertices.add((G) (new Integer(lp))); createAdjacencyLists(lstedge, Verticesnum); } // method to cretae a adjacency lists private void createAdjacencyLists(int[][] lstedge, int Verticesnum) { // code for linked list for (int lp = 0; lp < Verticesnum; lp++) { lstneighbors.add(new ArrayList<Integer>()); } for (int lp = 0; lp < lstedge.length; lp++) { int utx = lstedge[lp][0]; int vrtx = lstedge[lp][1]; lstneighbors.get(utx).add(vrtx);
  • 7. } } // method for adjacency lists private void createAdjacencyLists(List<Edge> lstedge, int Verticesnum) { // code for linked list for (int lp = 0; lp < Verticesnum; lp++) { lstneighbors.add(new ArrayList<Integer>()); } for (Edge edge : lstedge) { lstneighbors.get(edge.utx).add(edge.vrtx); } } // method to return the number of vertices public int getSize() { return lstvertices.size(); } //method to return the vertices public List<G> getVertices()
  • 8. { return lstvertices; } //method to return the specific vertex public G getVertex(int index) { return lstvertices.get(index); } //method to return the index of specific vertex public int getIndex(G g) { return lstvertices.indexOf(g); } //method to return the neighbour of specific vertex public List<Integer> getNeighbors(int index) { return lstneighbors.get(index); } //method to return the degree of specific vertex public int getDegree(int vrtx) {
  • 9. return lstneighbors.get(vrtx).size(); } //method to print the edges public void printEdges() { for (int utx = 0; utx < lstneighbors.size(); utx++) { System.out.print(getVertex(utx) + " (" + utx + "): "); for (int j = 0; j < lstneighbors.get(utx).size(); j++) { System.out.print("(" + utx + ", " + lstneighbors.get(utx).get(j) + ") "); } System.out.println(); } } // method to clear the graph public void clear() { lstvertices.clear(); lstneighbors.clear();
  • 10. } // method to add the vertex to graph public void addVertex(G g) { lstvertices.add(g); lstneighbors.add(new ArrayList<Integer>()); } // method to add an edge to the graph public void addEdge(int utx, int vrtx) { lstneighbors.get(utx).add(vrtx); lstneighbors.get(vrtx).add(utx); } //class edge public static class Edge { public int utx; public int vrtx; // constructor public Edge(int utx, int vrtx) { this.utx = utx; this.vrtx = vrtx;
  • 11. } } // dfs tree public Tree dfs(int vrtx) { List<Integer> ordrSearch = new ArrayList<Integer>(); int[] parnt = new int[lstvertices.size()]; for (int lp = 0; lp < parnt.length; lp++) parnt[lp] = -1; boolean[] isVst = new boolean[lstvertices.size()]; // Recursively search dfs(vrtx, parnt, ordrSearch, isVst); // Return a search tree return new Tree(vrtx, parnt, ordrSearch); } //method for the DFS search private void dfs(int vrtx, int[] parnt, List<Integer> ordrSearch, boolean[] isVst) { ordrSearch.add(vrtx); isVst[vrtx] = true; for (int lp : lstneighbors.get(vrtx))
  • 12. { if (!isVst[lp]) { parnt[lp] = vrtx; dfs(lp, parnt, ordrSearch, isVst); } } } // code for bfs public Tree bfs(int vrtx) { List<Integer> ordrSearch = new ArrayList<Integer>(); int[] parnt = new int[lstvertices.size()]; for (int lp = 0; lp < parnt.length; lp++) parnt[lp] = -1; java.util.LinkedList<Integer> queue = new java.util.LinkedList<Integer>(); boolean[] isVst = new boolean[lstvertices.size()]; queue.offer(vrtx); isVst[vrtx] = true; while (!queue.isEmpty()) { int utx = queue.poll(); ordrSearch.add(utx);
  • 13. for (int w : lstneighbors.get(utx)) { if (!isVst[w]) { queue.offer(w); parnt[w] = utx; isVst[w] = true; } } } return new Tree(vrtx, parnt, ordrSearch); } //class tree public class Tree { private int root; private int[] parnt; private List<Integer> ordrSearch; // Code for tree construction public Tree(int root, int[] parnt, List<Integer> ordrSearch) { this.root = root; this.parnt = parnt; this.ordrSearch = ordrSearch; }
  • 14. // method to return tree root public int getRoot() { return root; } // method to return parent public int getParent(int vrtx) { return parnt[vrtx]; } // // method to return search order public List<Integer> getSearchOrder() { return ordrSearch; } // method to return number of vertices public int getNumberOfVerticesFound() { return ordrSearch.size(); } // method to return vertices path public List<G> getPath(int index) { ArrayList<G> path = new ArrayList<G>(); do { path.add(lstvertices.get(index)); index = parnt[index];
  • 15. } while (index != -1); return path; } // // method to pritn the path public void printPath(int index) { List<G> path = getPath(index); System.out.print("A path from " + lstvertices.get(root) + " to " + lstvertices.get(index) + ": "); for (int lp = path.size() - 1; lp >= 0; lp--) System.out.print(path.get(lp) + " "); } // method to print whole tree public void printTree() { System.out.println("Root is: " + lstvertices.get(root)); System.out.print("Edges: "); for (int lp = 0; lp < parnt.length; lp++) { if (parnt[lp] != -1) { // Display an edge System.out.print("(" + lstvertices.get(parnt[lp]) + ", "
  • 16. + lstvertices.get(lp) + ") "); } } System.out.println(); } } } // Graph interface interface Graph<G> { // to get the number of vertices public int getSize(); // to get the vertices public java.util.List<G> getVertices(); // to get the object public G getVertex(int index); // to get index public int getIndex(G g); // to get neighbours public java.util.List<Integer> getNeighbors(int index); // // to get the degree public int getDegree(int vrtx); // to print the edges public void printEdges(); // to clear the graph public void clear();
  • 17. // to add the vertex into the graph public void addVertex(G g); // to add edge in the graph public void addEdge(int utx, int vrtx); // to perform dfs public AbstractGraph<G>.Tree dfs(int vrtx); // to perform bfs public AbstractGraph<G>.Tree bfs(int vrtx); } } Result: Enter a file name: data1.txt The number of vertices is 6 0 (0): (0, 1) (0, 2) 1 (1): (1, 0) (1, 3) 2 (2): (2, 0) (2, 3) (2, 4) 3 (3): (3, 1) (3, 2) (3, 4) (3, 5) 4 (4): (4, 2) (4, 3) (4, 5) 5 (5): (5, 3) (5, 4) The graph is connected