Question

In: Computer Science

Write a Java program that implements the Depth-First Search (DFS) algorithm. Input format: This is a...

Write a Java program that implements the Depth-First Search (DFS) algorithm.

Input format: This is a sample input from a user.

3

2

0 1

1 2

The first line (= 3 in the example) indicates that there are three vertices in the graph. You can assume that the first vertex starts from the number 0. The second line (= 2 in the example) represents the number of edges, and following two lines are the edge information. This is the graph with the input information.

Sample Run 0: Assume that the user typed the following lines

3

2

0 1

1 2

This is the correct output. Your program should display the mark array of DFS. For the problem, you can assume that the starting vertex is always 0. And also, you can assume that the graph is connected.

Mark[0]:1

Mark[1]:2

Mark[2]:3

Sample Run 1: Assume that the user typed the following lines

5

6

0 1

0 2

0 3

1 3

2 3

3 4

This is the correct output.

Mark[0]:1

Mark[1]:2

Mark[2]:5

Mark[3]:3

Mark[4]:4

Sample Run 2: Assume that the user typed the following lines

5

6

0 1

0 2

0 3

1 4

2 3

3 4

This is the correct output.

Mark[0]:1

Mark[1]:2

Mark[2]:4

Mark[3]:5

Mark[4]:3

Solutions

Expert Solution

// GraphDFS.java

import java.util.Scanner;

public class GraphDFS {
  
   private int n; // number of vertices
   private int data[][]; // adjacency matrix to represent the graph status
   private int mark[]; // array to store the order of visiting the vertices using DFS
   private int currentMark; // counter to store the current visitation number
  
   // constructor
   public GraphDFS(int n)
   {
       this.n = n;
       data = new int[n][]; // create data array of n rows
      
       mark = new int[n]; // create mark array of n rows
      
       // loop to set all entries of mark to 0 and data to 0
       for(int i=0;i<n;i++)
       {  
           mark[i] = 0;
           data[i] = new int[n]; // create n columns for ith row
           for(int j=0;j<n;j++)
               data[i][j] = 0;
       }
       currentMark = 0; // initialize currentMark to 0
   }
  
   // method to add an edge from ith node to jth node
   public void addEgde(int i, int j)
   {
       data[i][j] =1;
   }
  
   // method to implement Depth-First Search (DFS) algorithm starting from vertex 0
   public void DFS()
   {
       DFS(0);       // call the helper recursive method
      
       // loop to display the order in which the vertices was visited
       for(int i=0;i<n;i++)
           System.out.println("Mark["+i+"]:"+mark[i]);
   }
  
   //helper method to implement DFS traversal
   private void DFS(int src)
   {
       // src has been visited
       currentMark++; // increment currentMark
       mark[src]=currentMark; // set src entry of mark to currentMark
      
       // loop to determine the unvisited neighbors of src and perform DFS
       for(int i=0;i<data[src].length;i++)
       {
           // ith vertex is a neighbor and not visited yet, call DFS for vertex i
           if((data[src][i] == 1) && (mark[i] == 0))
               DFS(i);
       }
   }
  
   public static void main(String[] args) {
  
       GraphDFS g;
       Scanner scan = new Scanner(System.in);
       int numVertices, numEdges, startV, endV;
       // input number of vertices
       numVertices = scan.nextInt();
      
       // input number of edges
       numEdges = scan.nextInt();
      
       // create a graph for numVertices
       g = new GraphDFS(numVertices);
      
       // loop to input and add input edge to the graph
       for(int i=0;i<numEdges;i++)
       {
           startV = scan.nextInt();
           endV = scan.nextInt();
           g.addEgde(startV, endV);
       }
      
       // perform DFS
       g.DFS();
  
   }

}

// end of GraphDFS.java

Output:


Related Solutions

Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is similar to binary search, except it tries to begin the search nearer to the location of the item. Instead of the using the middle value of the sorted array, interpolation search estimates the location of the target with respect to the first & last values in the array. The implementation is the same as binary search except that you should calculate the mid value...
how to write program in java for encrypt and decrypt input text using DH algorithm
how to write program in java for encrypt and decrypt input text using DH algorithm
please write a C program that implements Quick Sort algorithm.
please write a C program that implements Quick Sort algorithm.
Write a Java program that implements the Number Guessing Game: 1. First generate a random number...
Write a Java program that implements the Number Guessing Game: 1. First generate a random number (int) between 0 and 100, call it N 2. Read user input (a guess) 3. check the number, if it's smaller than N, output "The number is larger than that" 4. If the input is larger than N, output "The number is smaller than that" 5. If the input is equal to N, output " You got it!", and exit 6. Repeat until the...
Java Write a program that will only accept input from a file provided as the first...
Java Write a program that will only accept input from a file provided as the first command line argument. If no file is given or the file cannot be opened, simply print “Error opening file!” and stop executing. A valid input file should contain two lines. The first line is any valid string, and the second line should contain a single integer. The program should then print the single character from the string provided as the first line of input...
1. Write a Java program that asks the user to input a positive integer n first,...
1. Write a Java program that asks the user to input a positive integer n first, then create an array of size n. Fill n random integers between 5 and 555, inclusively, into the created array. Output the sum of all the integers in the array and the average of all the integers in the array. 2 .Find the output of the following Java program and explain your answer
Write a program that implements the A* algorithm to find a path from any two given...
Write a program that implements the A* algorithm to find a path from any two given nodes. You may use any of the following languages: C++, C#, Java, ActionScript. Problem Overview & Algorithm Description In a fully-observable environment where there are both pathable and blocked nodes, an agent must find a good path from their starting node to the goal node. The agent must use the A* algorithm to determine its path. For this program, you must use the Manhattan...
Binary Search Algorithm a.) Create a Java application that utilizes the "Binary Search Algorithm" presented in...
Binary Search Algorithm a.) Create a Java application that utilizes the "Binary Search Algorithm" presented in chapter 19 (NOT Java's pre-built binarySearch() method from imported Java library) to search for an integer in a random array of size 30 in the range of 0 to 1000 inclusive. You should use Java's random number generator to randomize the numbers in your array. b.) The application's main() method should display unsorted array and sorted array, prompt user for a search key, allow...
Write a JAVA program called Convertor that has two methods. The first one converts an input...
Write a JAVA program called Convertor that has two methods. The first one converts an input binary into its equivalent decimal number. The second method converts a decimal number into its equivalent binary.​ binary2Decimal, decimal2Binary are the names for those methods.​ binary2Decimal receives a binary number as a string and returns a decimal number as an integer. And vice versa for the decimal2Binary method.​
Write a program to show the difference between linear search and binary search. Show the input...
Write a program to show the difference between linear search and binary search. Show the input test data for your program and the output produced by your program which clearly show that binary search is faster than linear search
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT