我试图计算BFS,但我想我无法将数字分配给数组。它正确地显示了排名,但得分部分没有增加。输出必须是“0 1 2 3 4 5”,这是正确的,但有一些错误。
public class BFS_DFS {
public static int[] BFS (int [][] graph) {
int[] output = {0};
int start=0;
int v=graph.length;//a[][] is adj matrix declared globally
boolean visited[]=new boolean[v];//indexing done from 1 to n
LinkedList<Integer> queue=new LinkedList<Integer>();
visited[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int x=queue.remove();
System.out.print(x+" ");
for(int j=graph.length;j<graph.length;j++){
output[j-1]=x;
}
for (int i=1; i < v; i++)
if((graph[x][i] == 1) && (!visited[i]))
{
queue.add(i);
visited[i]=true;
}
}
return output ; }
public static void main(String[] args) {
//DO NOT WRITE ANY CODE IN MAIN METHOD
int [][] graph={{0,1,1,1,0,0},{1,0,0,0,1,1},{1,0,0,0,0,1},{1,0,0,0,0,0},{0,1,0,0,0,0},{0,1,1,0,0,0}};
int [] BFSresult={0,1,2,3,4,5};
int [] DFSresult={0,1,4,5,2,3};
int grade=0;
if (Arrays.equals(BFS(graph),BFSresult )) {
System.out.println("BFS is working correctl");
grade+=50;
}
else
System.out.println("BFS is not working correctly");
if (Arrays.equals(DFS(graph),DFSresult )) {
System.out.println("DFS is working correctl");
grade+=50;
}
else
System.out.println("DFS is not working correctly");
System.out.println("Your grade is->"+grade);
}
}