Question
How to implement the DFS of a graph import java.util.Arrays; import java.util.Scanner; import java.util.Vector; import java.io.File; public class DFS{ /* DFS(G) Given an adjacency matrix
How to implement the DFS of a graph
import java.util.Arrays; import java.util.Scanner; import java.util.Vector; import java.io.File;
public class DFS{
/* DFS(G) Given an adjacency matrix describing a graph, print the listing of vertices encountered by a depth-first search starting at vertex 0. */ public static void DFS(int[][] G){ int n = G.length;
/* ... Your code here ... */ } /* main() Contains code to test the DFS method. */ public static void main(String[] args){ Scanner s; if (args.length > 0){ try{ s = new Scanner(new File(args[0])); } catch(java.io.FileNotFoundException e){ System.out.printf("Unable to open %s ",args[0]); return; } System.out.printf("Reading input values from %s. ",args[0]); }else{ s = new Scanner(System.in); System.out.printf("Reading input values from stdin. "); } int graphNum = 0; double totalTimeSeconds = 0; //Read graphs until EOF is encountered (or an error occurs) while(true){ graphNum++; if(graphNum != 1 && !s.hasNextInt()) break; System.out.printf("Reading graph %d ",graphNum); int n = s.nextInt(); int[][] G = new int[n][n]; int valuesRead = 0; for (int i = 0; i < n && s.hasNextInt(); i++){ for (int j = 0; j < n && s.hasNextInt(); j++){ G[i][j] = s.nextInt(); valuesRead++; } } if (valuesRead < n*n){ System.out.printf("Adjacency matrix for graph %d contains too few values. ",graphNum); break; } long startTime = System.currentTimeMillis(); DFS(G.clone()); long endTime = System.currentTimeMillis(); totalTimeSeconds += (endTime-startTime)/1000.0; } graphNum--; System.out.printf("Processed %d graph%s. Average Time (seconds): %.2f ",graphNum,(graphNum != 1)?"s":"",(graphNum>0)?totalTimeSeconds/graphNum:0); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started