Question

Help !! I need help with Depth-First Search using an undirected graph.

Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given.

Write a driver program, which reads input file mediumG.txt as an undirected graph and runs

the depth-first search algorithm to find paths to all the other vertices considering 0 as the

source. This driver program should display the paths in the following manner:

0 to ‘v’: list of all the vertices traversed to go to v from 0, separated by ‘,’ . There is another

file called tinyG.txt which you can use for your testing purpose.

DFS(G) 1 for each vertex u E G.V 2 u.colorWHITE 4 time=0 5 for each vertex u E G. V 6 if u.color WHITE DFS-VISIT (G, u) DFS-V

Graph.java

import java.io.BufferedReader;

import java.io.IOException;

import java.util.Arrays;

import java.util.LinkedList;

import java.util.StringTokenizer;

/**

* This is a super class represents a graph.

*/

public class Graph {

public int V; // the number of vertex of tihs graph

public int E; // the number of edges of this graph

public LinkedList<Integer>[] adj; // the list to store the adjacent

vertices

/**

* Constructor, initiate V and E to 0.

*/

public Graph()

{

V = 0;

E = 0;

}

/**

* Constructor, read from a file and construct a new graph

* @param reader the file buffer reader

* @throws IOException

*/

public Graph(BufferedReader reader) throws IOException

{

String line;

line = reader.readLine();

V = Integer.parseInt(line);

line = reader.readLine();

E = Integer.parseInt(line);

adj = new LinkedList[V];

for (int v = 0; v < V; v++) {

adj[v] = new LinkedList<Integer>();

}

while ((line = reader.readLine()) != null) {

int tempV1, tempV2;

StringTokenizer st = new StringTokenizer(line, " ");

tempV1 = Integer.parseInt(st.nextToken());

tempV2 = Integer.parseInt(st.nextToken());

addEdge(tempV1, tempV2);

}

}

/**

* add an edge to the graph

* @param v one vertex of an edge

* @param w the other vertex of an edge

*/

public void addEdge(int v, int w) {

}

/**

* Convert the graph to string.

* @return a string represents the adjacent list of this graph

*/

public String toString()

{

String s = new String();

s = "There are "+V+" vertices and "+E+" edges\n";

for(int i=0;i<V;i++)

{

s = s+i+": ";

for(int j = 0; j<adj[i].size();j++)

{

s = s+adj[i].get(j)+" ";

}

s = s+"\n";

}

return s;

}

}

TinyDG.txt

13
22
4 2
2 3
3 2
6 0
0 1
2 0
11 12
12 9
9 10
9 11
7 9
10 12
11 4
4 3
3 5
6 8
8 6
5 4
0 5
6 4
6 9
7 6

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • Points to be taken care of :
  1. i just used the data that is provided in TinyDG.txt. if you have to use any other file please change the file name in the code.
  2. If you provide any wrong destination , that is there is no any path from that source 0 to your given destination then program will give output as "No path found from source 0 to destination" else it will display the comma separated traversed node form source 0 to given destination.
  3. In my code i am using destination as 5 , you can test it with any destination by just changing the value of destination in the code DFS(graphObject.adj,5) , here 5 is the destination
  4. i just include "DFSTraversal" class which is responsible for all the DFS operation.
  • code ;
  • --------

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;

/**
* This is a super class represents a graph.
*/

public class Graph {
public int V; // the number of vertex of tihs graph
public int E; // the number of edges of this graph
public LinkedList<Integer>[] adj; // the list to store the adjacent vertices

/**
* Constructor, initiate V and E to 0.
*/
public Graph()
{
V = 0;
E = 0;
}
  
/**
* Constructor, read from a file and construct a new graph
* @param reader the file buffer reader
* @throws IOException
*/
public Graph(BufferedReader reader) throws IOException
{
String line;
line = reader.readLine();
V = Integer.parseInt(line);
line = reader.readLine();
E = Integer.parseInt(line);
adj = new LinkedList[V];
for (int v = 0; v < V; v++)
{
adj[v] = new LinkedList<Integer>();
}
while ((line = reader.readLine()) != null)
{
int tempV1, tempV2;
StringTokenizer st = new StringTokenizer(line, " ");
tempV1 = Integer.parseInt(st.nextToken());
tempV2 = Integer.parseInt(st.nextToken());
addEdge(tempV1, tempV2);
}
}

/**
* add an edge to the graph
* @param v one vertex of an edge
* @param w the other vertex of an edge
*/
public void addEdge(int v, int w) {
this.adj[v].add(w);
}

/**
* Convert the graph to string.
* @return a string represents the adjacent list of this graph
*/
public String toString()
{
String s = new String();
s = "There are "+V+" vertices and "+E+" edges\n";
for(int i=0;i<V;i++)
{
s = s+i+": ";
for(int j = 0; j<adj[i].size();j++)
{
s = s+adj[i].get(j)+" ";
}
s = s+"\n";
}
return s;
}
  
}
class DFSTraversal
{
static String NodeColour[];
static String visitedNode =""; // variable that track the list of visited node from source to destrination
static boolean reachedDestination = false;
public static void DFS( LinkedList<Integer> G[] , int destination)
{
int size = G.length; // getting the number of vertices
NodeColour = new String[size];
// initialising the coulur of node to WHITE initially
for( int i=0;i<size;i++)
{
NodeColour[i] = "WHITE";
}
System.out.println("Below is the list of node traversed from source 0 to destination "+ destination);
  
DFSVisit(G,0,destination);
if(!reachedDestination)
System.out.println(" \nNo path found from source 0 to destination "+ destination);
else
System.out.print( "0 to \'"+destination+"\' : "+visitedNode);
}
public static void DFSVisit(LinkedList<Integer> G[] , int node, int destination)
{
// if visited node is our destination then return from function , do nothing
if (node == destination)
{

visitedNode = visitedNode.concat(node+",");
reachedDestination = true;
return;
}
NodeColour[node] = "GRAY"; // maing colour of visited node to GRAY
visitedNode = visitedNode.concat(node+",");

// traverse each adjacent node of visited node
LinkedList<Integer> list = G[node];
for(int v : list)
{
if (NodeColour[v].equals("WHITE"))
{
DFSVisit(G , v,destination);
}
}
// make colour of processed node to BLACK
NodeColour[node] = "BLACK";
  
}
public static void main(String args[]) throws Exception
{
// reading data from TinyDG.txt
BufferedReader br = new BufferedReader(new FileReader("TinyDG.txt"));
Graph graphObject = new Graph(br);
System.out.println(graphObject.toString());
// traverse the node from source 0 to destination 5
DFS(graphObject.adj,5);
}
}

  • output of the screenshot

C: \Userslabhayk3x Desktop>java DFSTraversal There are 13 vertices and 22 edges 2: 3 0 3: 2 5 4: 2 3 6: 0 849 7: 9 6 9: 10 11

Add a comment
Know the answer?
Add Answer to:
Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • How can I solved my Java Program for DelivC

    //Graph Class: import java.util.ArrayList; //Graph is a class whose objects represent graphs.  public class Graph {     ArrayList<Node> nodeList;     ArrayList<Edge> edgeList;         public Graph() {         nodeList = new ArrayList<Node>();         edgeList = new ArrayList<Edge>();         }         public ArrayList<Node> getNodeList() {         return nodeList;    }    public ArrayList<Edge> getEdgeList() {         return edgeList;    }    public void addNode(Node n) {         nodeList.add(n);    }    public void addEdge(Edge e) {         edgeList.add(e);    }    public String toString() {         String s = "Graph g.\n";         if (nodeList.size() > 0) {             for (Node n : nodeList) {         // Print node info         String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";         s = s.concat(t);         }         s = s.concat("\n");             }         return s;     }  } // Node Class: import java.util.ArrayList;  // Node is a class whose objects represent nodes (a.k.a., vertices) in the graph.  public class Node {    String name;     String val; // The value of the Node     String abbrev; // The abbreviation for the Node     ArrayList<Edge> outgoingEdges;     ArrayList<Edge> incomingEdges;             String color; //Create the color of the TYPE Node List     int start; //Create the Starting Time     int end; //Create the Ending Time             public Node( String theAbbrev ) {         setAbbrev( theAbbrev );         val = null;         name = null;         outgoingEdges = new ArrayList<Edge>();         incomingEdges = new ArrayList<Edge>();     }         public String getAbbrev() {         return abbrev;     }         public String getName() {         return name;     }         public String getVal() {         return val;     }         public ArrayList<Edge> getOutgoingEdges() {         return outgoingEdges;     }         public ArrayList<Edge> getIncomingEdges() {         return incomingEdges;...

  • I need help with adding comments to my code and I need a uml diagram for...

    I need help with adding comments to my code and I need a uml diagram for it. PLs help.... Zipcodeproject.java package zipcodesproject; import java.util.Scanner; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Zipcodesproject { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input=new Scanner(System.in); BufferedReader reader; int code; String state,town; ziplist listOFCodes=new ziplist(); try { reader = new BufferedReader(new FileReader("C:UsersJayDesktopzipcodes.txt")); String line = reader.readLine(); while (line != null) { code=Integer.parseInt(line); line =...

  • Show how depth-first search works on the graph of Figure 22.6. Assume that the for loop of lines 5–7 of the DFS proced...

    Show how depth-first search works on the graph of Figure 22.6. Assume that the for loop of lines 5–7 of the DFS procedure considers the vertices in reverse alphabetical order, and assume that each adjacency list is ordered alphabetically. Show the discovery and finishing times for each vertex, and show the classification of each edge. DIJKSTRA(G,w,s) 1INITIALIZE-SINGLE-SOURCE(G,s) 2 S ?? 3 Q ? V[G] 4 while Q =? 5 do u ? EXTRACT-MIN(Q) 6 S ? S?{u} 7 for each...

  • in Java Write a program DFSTrace that contains a version of a depth first search that...

    in Java Write a program DFSTrace that contains a version of a depth first search that prints a trace of its traversal. Write a public static method: public static void dfsPrintTrace(Graph g) { // *** Declare and initialize the marked array. dfsPrintTrace(g, 0, marked, 0); } This method calls a private method: private static void dfsPrintTrace(Graph g, int start, boolean[] marked, int indent) All references to a method below refer to this second method. Every message printed should be preceded...

  • Question 1: Given an undirected connected graph so that every edge belongs to at least one...

    Question 1: Given an undirected connected graph so that every edge belongs to at least one simple cycle (a cycle is simple if be vertex appears more than once). Show that we can give a direction to every edge so that the graph will be strongly connected. Question 2: Given a graph G(V, E) a set I is an independent set if for every uv el, u #v, uv & E. A Matching is a collection of edges {ei} so...

  • How to solve my code for my Deliv C program?

    ProgramIntro.pngProgramIntro2.pngProgramIntro1.pngProgram1.pngProgram2.pngGraph Class:import java.util.ArrayList;//Graph is a class whose objects represent graphs. public class Graph {    ArrayList<Node> nodeList;    ArrayList<Edge> edgeList;       public Graph() {        nodeList = new ArrayList<Node>();        edgeList = new ArrayList<Edge>();       }       public ArrayList<Node> getNodeList() {        return nodeList;   }   public ArrayList<Edge> getEdgeList() {        return edgeList;   }   public void addNode(Node n) {        nodeList.add(n);   }   public void addEdge(Edge e) {        edgeList.add(e);   }   public String...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT