Question: This is the first part of this program. THIS PART HAS ALREADY BEEN COMPLETED. Continue with your program from above and add the following: 1.
This is the first part of this program. THIS PART HAS ALREADY BEEN COMPLETED.
Continue with your program from above and add the following:
1. Dijkstra's Algorithm
2. Prim's Algorithm
3. Floyd's (find all reachable paths with a directed graph start with adjacency matrix)
4. Floyd and Warsall's (Find shortest path).
Here is the code:
**************************************
Graph.java
import java.io.Serializable;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Graph {
int[][] matrix; //for adjacency matrix
int rows;
int columns;
Boolean[] visited; //for search algorithms, you'll figure out it later in code.
public Graph() throws FileNotFoundException {
Scanner scan = new Scanner(new File("adj.txt")); //open file
rows = 5;
columns = 5;
matrix = new int[rows][columns];
while (scan.hasNext()) {
while (scan.hasNextLine()) {
for (int i = 0; i
String[] line = scan.nextLine().trim().split(" "); //read a line and trim it using spaces.
for (int j = 0; j
matrix[i][j] = Integer.parseInt(line[j]); //enter trimmed array onto matrix.
}
}
}
}/ow we have our matrix loaded from file.
}
public void BFS(int start) {
Queue
visited = new Boolean[rows];
for (int i = 0; i 0) //check for valid start {
queue.add(start); //add start to queue
System.out.println("Order of traversal " + start);
visited[start] = true;
while (queue.size() != 0) //pop first node from queue, look into matrix for unvisited nodes reachable from current node and put it in queue. {
int j = queue.remove();
for (int i = 0; i
if (visited[i] != true && matrix[j][i] != 0) {
visited[i] = true;
queue.add(i);
System.out.println(i);
}
}
}
}
}
public void DFS(int start) {
if (start 0) //check for a valid start node {
visited = new Boolean[rows];
for (int i = 0; i
System.out.println("Order of traversal " + start);
visited[start] = true;
for (int i = 0; i
}
public void depthVisit(int node) {
System.out.println(node);
visited[node] = true;
for (int i = 0; i
depthVisit(i); //recursive call
} }
}
}
*******************************************
Fs.java
import java.io.FileNotFoundException;
public class Fs {
public static void main(String s[]) throws FileNotFoundException {
Graph G = new Graph();
System.out.println("BFS");
G.BFS(1);
System.out.println(" DFS");
G.DFS(1);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
