Question

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 by the number of spaces specified by the indent parameter. A recursive call should pass an indent value with 1 added.

The first time the method visits a vertex, it should print the message "First time at vertex n", where n is the integer label of the vertex.

Every other time it visits a vertex, it should print the message "Visiting vertex n again".

When it exits, it should print the message "Finished searching from n".

Here's the output when run on the file data/tinyG.txt:

First visit to 0.
 First visit to 6.
  Visited 0 again.
  First visit to 4.
   First visit to 5.
    First visit to 3.
     Visited 5 again.
     Visited 4 again.
    Finished with 3.
    Visited 4 again.
    Visited 0 again.
   Finished with 5.
   Visited 6 again.
   Visited 3 again.
  Finished with 4.
 Finished with 6.
 First visit to 2.
  Visited 0 again.
 Finished with 2.
 First visit to 1.
  Visited 0 again.
 Finished with 1.
 Visited 5 again.
Finished with 0.

Here's the main method to insert into your program to test your method(s):

        public static void main(String[] args) {
                In input = new In("data/tinyG.txt");
                Graph g = new Graph(input);

                dfsPrintTrace(g);
        }

Include in the comments of your code the answer to this question: What is the pattern formed by the "First visit" and "Finished" messages?

tinyG.txt

13

13

0 5

4 3

0 1

9 12

6 4

5 4

0 2

11 12

9 10

0 6

7 8

9 11

5 3

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// import the necessary package

import java.util.*;

// declare the class graph.

public class Graph

{

// Declare the variable.

private static int V;

private static LinkedList<Integer> adj[];

// Constructor of the class

Graph(int v)

{

// Assign value

V = v;

// Declare linklist

adj = new LinkedList[v];

// Start the for loop

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

// create new linklist.

adj[i] = new LinkedList();

}

// definition of the method

void addEdge(int v, int w)

{

// adding edge to graph

adj[v].add(w);

}

// Definition of the method

public static void dfsPrintTrace(Graph g)

{

// Declare an boolean array.

boolean marked[] = new boolean[V];

//display the statement on console.

System.out.println("Starting from vertex 0");

// start the for loop.

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

// check whether the value in array

// is false or not.

if (marked[i] == false)

// Call to the method

dfsPrintTrace(g, 0, marked, 0);

}

// definition of the method

private static void dfsPrintTrace(Graph g, int start,

boolean[] marked, int indent)

{

// declare variable

int n=0;

// set the value of the starting

// value of array to be true.

marked[start] = true;

// traversing the graph

Iterator<Integer> i = adj[start].listIterator();

// Start the while loop

while (i.hasNext())

{

// set the value of n.

n = i.next();

if (!marked[n])

{

// display the statement on console.

System.out.println(

"First time at vertex " + n);

// call to the method.

dfsPrintTrace(g, n, marked, indent++);

}

else

{

// Display the statement on console.

System.out.println(

"Visiting vertex " + n + " again");

}

}

// display the statement on console.

System.out.println(

"Finished searching from " + n);

}

// start the main method.

public static void main(String args[])

{

// declare the object of graph

Graph g = new Graph(4);

// Add edges to graph.

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

// Display the statement on console.

System.out.println("Depth First Traversal");

// Call to the method.

g.dfsPrintTrace(g);

}

}

Add a comment
Answer #1

// import the necessary package

import java.util.*;

// declare the class graph.

public class Graph

{

// Declare the variable.

private static int V;

private static LinkedList<Integer> adj[];

// Constructor of the class

Graph(int v)

{

// Assign value

V = v;

// Declare linklist

adj = new LinkedList[v];

// Start the for loop

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

// create new linklist.

adj[i] = new LinkedList();

}

// definition of the method

void addEdge(int v, int w)

{

// adding edge to graph

adj[v].add(w);

}

// Definition of the method

public static void dfsPrintTrace(Graph g)

{

// Declare an boolean array.

boolean marked[] = new boolean[V];

//display the statement on console.

System.out.println("Starting from vertex 0");

// start the for loop.

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

// check whether the value in array

// is false or not.

if (marked[i] == false)

// Call to the method

dfsPrintTrace(g, 0, marked, 0);

}

// definition of the method

private static void dfsPrintTrace(Graph g, int start,

boolean[] marked, int indent)

{

// declare variable

int n=0;

// set the value of the starting

// value of array to be true.

marked[start] = true;

// traversing the graph

Iterator<Integer> i = adj[start].listIterator();

// Start the while loop

while (i.hasNext())

{

// set the value of n.

n = i.next();

if (!marked[n])

{

// display the statement on console.

System.out.println(

"First time at vertex " + n);

// call to the method.

dfsPrintTrace(g, n, marked, indent++);

}

else

{

// Display the statement on console.

System.out.println(

"Visiting vertex " + n + " again");

}

}

// display the statement on console.

System.out.println(

"Finished searching from " + n);

}

// start the main method.

public static void main(String args[])

{

// declare the object of graph

Graph g = new Graph(4);

// Add edges to graph.

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

// Display the statement on console.

System.out.println("Depth First Traversal");

// Call to the method.

g.dfsPrintTrace(g);

}

}

Add a comment
Know the answer?
Add Answer to:
in Java Write a program DFSTrace that contains a version of a depth first search that...
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
  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    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...

  • Please follow all the instructions and do all the parts (a-d)! Create a Java program which implem...

    Please follow all the instructions and do all the parts (a-d)! Create a Java program which implements Dijkstra’s shortest path algorithm according to the psueudocode below. Base the design on the weighted graph implementation used in Problem3.java (provided at the bottom). Your program should include the following features: a. A new method receives a starting vertex index and a target vertex index (e.g. 0 and 4). It computes the shortest distances to all vertexes using Dijkstra’s algorithm. The pseudocode is...

  • 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 =...

  • Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is...

    Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is much appreciated. read a set of data representing a directed, unweighted graph build an in-memory graph structure using the data display the graph using depth-first traversal display the graph using breadth-first traversal Input data - The data consists of records like this: 16 3 15 4 -1 This represents a vertex 16 with neighbors 3, 15, and 4. The -1 is the indicator that...

  • Java 1. Write a getCount method in the IntArrayWorker class that returns the count of the...

    Java 1. Write a getCount method in the IntArrayWorker class that returns the count of the number of times a passed integer value is found in the matrix. There is already a method to test this in IntArrayWorkerTester. Just uncomment the method testGetCount() and the call to it in the main method of IntArrayWorkerTester. 2. Write a getLargest method in the IntArrayWorker class that returns the largest value in the matrix. There is already a method to test this in...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  • Hello Guys. I need help with this its in java In this project you will implement...

    Hello Guys. I need help with this its in java In this project you will implement a Java program that will print several shapes and patterns according to uses input. This program will allow the use to select the type (say, rectangle, triangle, or diamond), the size and the fill character for a shape. All operations will be performed based on the user input which will respond to a dynamic menu that will be presented. Specifically, the menu will guide...

  • Have to write the tree into a text file? JAVA CODE Binary search tree This is...

    Have to write the tree into a text file? JAVA CODE Binary search tree This is the tree public class Buildbst { private int data; private Buildbst left; private Buildbst right; //Set the binary search tree public Buildbst(int data) { this.data = data; this.left = null; this.right =null; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Buildbst getLeft() { return left; } public void setLeft(Buildbst left) { this.left = left;...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

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