Question: longest shortest path using dfs in java programming: I am halfway through this coding problem, it solves some arrays, but the 2 D array in

longest shortest path using dfs in java programming: I am halfway through this coding problem, it solves some arrays, but the 2D array in the picture return an error of out of bounds. help me fix it please. here is my code:
abstract class:
public abstract class LSD {
public abstract int distance (int[][] array);
}
Rest of the code:
public class pathlengthcalculation extends LSD {
public int[][] array;
public pathlengthcalculation(){
// Constructor implementation (if needed)
}
public pathlengthcalculation(int[][] array){
this.array = array;
}
@Override
public int distance(int[][] array){
int longestDistance =-1;
for (int i =0; i array.length; i++){
for (int j =0; j array[i].length; j++){
int startVertex = array[i][j];
int distance = bfsShortestPath(array, startVertex);
if (distance > longestDistance){
longestDistance = distance;
}
}
}
return longestDistance;
}
private int bfsShortestPath(int[][] array, int start){
int[] queue = new int[array.length];
boolean[] visited = new boolean[array.length];
int[] distance = new int[array.length];
int front =0;
int rear =0;
queue[rear++]= start;
visited[start]= true;
distance[start]=0;
while (front rear){
int current = queue[front++];
for (int neighbor : array[current]){
if (!visited[neighbor]){
visited[neighbor]= true;
queue[rear++]= neighbor;
distance[neighbor]= distance[current]+1;
}
}
}
int maxDistance =0;
for (int d : distance){
if (d > maxDistance){
maxDistance = d;
}
}
return maxDistance;
}
public static void main(String[] args){
int[][] array ={{0,1},{0,2},{0,4},{1,3},{1,4},{2,5}};
//int[][] array ={{0,1},{0,2},{0,4},{1,3},{1,4},{2,5},{6,7}};
pathlengthcalculation instance = new pathlengthcalculation(array);
int longestShortestPath = instance.distance(array);
System.out.println("longest shortest path: "+longestShortestPath);
}
}
 longest shortest path using dfs in java programming: I am halfway

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!