Question

In: Computer Science

create a code in JAVA that takes arguments to do a bfs(breadth first search) or a...

create a code in JAVA that takes arguments to do a bfs(breadth first search) or a dfs( depth first search) using a txt file as the graph input.

I have made most of the main function as well as a nose function I just need the bfs and dfs functions to work here's what I have so far, the comments that start with TODO are the parts that I need to finish

Main.java

import java.io.*;
import java.util;
ArrayList; import java.util.Iterator;
import java.util.List;

public class Main {
//class variables
private static boolean extendedOn;
public static String [] arr;
public static List<Node> nodeList;
public static Node firstNode;
public static int vertices;
//main method
public static void main(String[]args){
//the int for the arguments
int argument = 0;
int destination;
extendedOn = false;
boolean isDfs = false;
//checks to make sure that the user specified the destination
if(args[argument].equals("-dest")){
argument++;
try { destination = Integer.parseInt(args[argument]); argument++; }catch (Exception e{
System.out.println("Wrong Argument, needs an integer");
System.exit(0); } }
else{ System.out.println("Please specify the destination using -dest");
System.exit(0); }
//if the first arg is -e if(args[argument].equals("-e")){ argument++; extendedOn = true; }
//if args is dfs if(args[argument].equals("-dfs")){ argument++; isDfs = true; }
//if the args is -bfs else if(args[argument].equals("-bfs")){ argument++; isDfs = false; }
else{
System.out.println("Requires a Search Argument"); System.exit(0); }
//the argument that gets the file
File file = new File( args[argument] ); instantiateList(file); //gets the initial time Long timeStart = System.currentTimeMillis();
//figures out whether to do dfs or bfs
if(isDfs){ DFS(firstNode); }
else{ BFS(); }
//gets the endingTime Long timeEnd = System.currentTimeMillis(); System.out.println("\nTime Taken: " + (timeEnd - timeStart)); }

//method that populates the node list with how many vertices there are
private static void instantiateNodes(){
for(int y = 1; y <= vertices; y++){
nodeList.add(new Node(y)); }
firstNode = nodeList.get(0); }
//method to instantiate the List
public static void instantiateList(File file){
vertices = 0;
//String [] arr; //= new String[0];
//reads the file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
//gets the vertices then creates the array which the buffered reader will put the values into
vertices = Integer.parseInt(br.readLine());
arr = new String[vertices];
int counter = 0;
//puts the values in String line = null;
while ((line = br.readLine()) != null)
{ arr[counter++] = line; } }
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
//prints out the vertices and initializes the nodeList
System.out.println("\nVertices: " + vertices);
nodeList = new ArrayList<>(); instantiateNodes();
//for loop
for(int x = 0; x < vertices; x++){
//populates a list with the vertexes
String line = arr[x];
List adjacentVertexes = new ArrayList();
//while the line is not empty put it in the list
while(!line.isEmpty())
{ String vertex;
//if there are multiple vertexes
if(line.contains(" "))
{ vertex = line.substring(0, line.indexOf(" "));
//gets the node from the node list and adds it to the Node's adjacency List adjacentVertexes.add(nodeList.get( (Integer.parseInt(vertex)) - 1 )); }
//if there is only one vertex left else{ adjacentVertexes.add(nodeList.get( (Integer.parseInt(line)) - 1 ));
line = ""; break; } //changes the line to the next vertex line = line.substring(line.indexOf(" ")+1); }
//creates the node and initializes it
Node newNode = nodeList.get( ((Node)adjacentVertexes.get(0)).getVertex() - 1 );
//removes the name of the vertex and sets it's list adjacentVertexes.remove(0); newNode.setList(adjacentVertexes);
//adds the newNode to the list of Nodes nodeList.add(newNode); } }
//TODO method for the BFS
public static void BFS(){ System.out.println("BFS:"); }
//TODO method for the DFS
public static void DFS(){ System.out.println("DFS:"); } } }

Node.java

import java.util.List;
public class Node {    
//variable for if the node has been visited before     private boolean hasBeenSearched;   
 private List<Node> adjacency;    
private int vertex;    
public int searched;    
public Node(int v){      
 vertex = v;        
hasBeenSearched = false;     }    
//gets the vertex of the node    
public int getVertex(){        
return vertex;     }    
//sets the variables for if the node has already been searched    
public void setSearch(boolean search){         hasBeenSearched = search;     }    
//gets the varaible for the search of the node     public boolean getSearch(){     
   return hasBeenSearched;     }    
//method used to set the list full of nodes    
public void setList(List<Node> nodeList){         adjacency = nodeList;     }    
//method used to get the Node from the list     public Node getNode(int index){       
  return adjacency.get(index);     }    
//method used to get the size of the adjacency list     public int getSize(){         return adjacency.size();     } }

Solutions

Expert Solution

There are two ways for representing a graph.

1. Using Neighbours list

2. Using Adjacency Matrix

In the methods below we have used Neighbours list approach.

*I would recommend you to use 'Queue' instead of 'List'

BFS:

public static void bfs(Node node)
{
   nodeList.add(node); //to add node in the node list
   node.visited=true;
   while (!nodeList.isEmpty())
   {

       Node element=nodeList.remove(); //to delete the node element
       System.out.print(element.data + "t");
       List<Node> neighbours=element.getNeighbours(); //to get neighbour nodes data
       for (int i = 0; i < neighbours.size(); i++) {
           Node n=neighbours.get(i);
           if(n!=null && !n.visited)
           {
               nodeList.add(n);
               n.visited=true;
           }
       }

   }
}

DFS:

There two ways for implementing DFS:

  • Recursive DFS
  • Iterative DFS using stack

1. Recursive DFS:

public static void dfs(Node node)

{

System.out.print(node.data + " ");

List<Node> neighbours=node.getNeighbours();

        node.visited=true;

for (int i = 0; i < neighbours.size(); i++) {

Node n=neighbours.get(i);

if(n!=null && !n.visited)

{

dfs(n);

}

}

}

2. Iterative DFS using stack:

public static void dfsUsingStack(Node node)

{

Stack<Node> stack=new  Stack<Node>();

stack.add(node);

while (!stack.isEmpty())

{

Node element=stack.pop();

if(!element.visited)

{

System.out.print(element.data + " ");

element.visited=true;

}

List<Node> neighbours=element.getNeighbours();

for (int i = 0; i < neighbours.size(); i++) {

Node n=neighbours.get(i);

if(n!=null && !n.visited)

{

stack.add(n);

}

}

}

}

Thanks!


Related Solutions

Using JAVA: Create a simple numeric code class SimpleCode that takes a set of numbers and...
Using JAVA: Create a simple numeric code class SimpleCode that takes a set of numbers and turns them into words and sentences. The code should use the 0 to represent a space between words and 00 to represent a period at the end of a sentence. The 26 letters of the alphabet should be represented in reverse order. In other words, Z is 26 and A is one. In your final product, only the first letter of a sentence should...
I need the output of the code like this in java First we create a new...
I need the output of the code like this in java First we create a new building and display the result: This building has no apartments. Press enter to continue......................... Now we add some apartments to the building and display the result: This building has the following apartments: Unit 1 3 Bedroom Rent $450 per month Currently unavailable Unit 2 2 Bedroom Rent $400 per month Currently available Unit 3 4 Bedroom Rent $1000 per month Currently unavailable Unit 4...
JavaScript Write a function called "first" that takes in two arguments - the first is an...
JavaScript Write a function called "first" that takes in two arguments - the first is an argument called arr that is an array of numbers, the second is an optional number argument called num(hint: you'll need a default value - look back at the slides). If "num" was not passed in (since it's optional), the "first" function will return an array containing the first item of the array. If a value for "num" was given, the "first" function will return...
1. What is the role of “levels” within a breadth-first search? 2. Other than flight routes,...
1. What is the role of “levels” within a breadth-first search? 2. Other than flight routes, what is an example of directed graphs in the real world? 3. Other than driving routes, what is an example of shortest paths in the real world? 4. What is the difference between shortest path and minimum spanning trees? 5. What role does “NP” play when developing efficient algorithms?
a java code In this lab you will implement an inorder traversal, and a search for...
a java code In this lab you will implement an inorder traversal, and a search for a 2-3-4 tree. The inorder traversal will print the contents (integers) of the tree, and the search method will return a boolean, indicating whether a given key was found in the tree. Examine the provided template. The main method is provided for you, as well as a template of the Node and 2-3-4 classes. The main method will read either "inorder" or an integer...
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...
Need to make Java code as following: Create a dice playing threading program to do the...
Need to make Java code as following: Create a dice playing threading program to do the following: 1. Start a thread for a process to simulate a computer rolling a die 1000 times. 2. Start another thread for a process to simulate a user rolling a die 1000 times. 3. Keep track of rolls for user and computer in an array(s). 4. Display on screen when the computer thread starts, the rolls, and when the computer thread ends. 5. Display...
Using the main function’s arguments, create a program that takes in a person’s name, their home...
Using the main function’s arguments, create a program that takes in a person’s name, their home town/location, and cell number then prints out the following message: Sample run 1: Java lab01_task03 Sililo Uis 0819876543 Output:   Contact successfully saved !! Contact Name : Sililo @ Uis Home number: 0819876543
Using Java programming, Write a LinkedList method swap() that takes two ints as arguments and swaps...
Using Java programming, Write a LinkedList method swap() that takes two ints as arguments and swaps the elements at those two positions. The method should not traverse the list twice to find the elements, and it should not create or destroy any nodes.
Create a program with the Calculator.java code RUN the program with the invalid data arguments 1,...
Create a program with the Calculator.java code RUN the program with the invalid data arguments 1, 3, 5x Take a screenshot of the output and describe what you think happened. MODIFY the code as in listing 14.2, NewCalculator.java , RUN it again with the same invalid input Take a screenshot of the new output and describe in your word document why you think the exception handling is a 'better' programming technique than just letting the program crash. __________________________________________________________________________ The Calculator.java...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT