gpt4 book ai didi

java - 给定图上无向图 BFS 的 “Adjacency Matrix” 表示并输出顶点

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:31 25 4
gpt4 key购买 nike

我可以在二维数组数组中找到BFS和DFS值,但是得分没有增加。我无法确切地弄清楚我做错了哪一部分。当我打印应该的值时,排序是正确的。但成绩仍然是 0。我愿意接受你的想法。

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);
}
}

最佳答案

数组(int[]输出)不适合存储未知长度的结果,因为它具有固定长度。
使用像List这样的集合来代替:

public static int[] BFS (int [][] graph) {

//you do not know what is the path length so use a List
List<Integer> output = new ArrayList<>();
int start=0;

int v=graph.length;
boolean visited[]=new boolean[v];//indexing done from 1 to n
LinkedList<Integer> queue=new LinkedList<>();
visited[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int x=queue.remove();
System.out.print(x+" ");
output.add(x); //add to output

for (int i=1; i < v; i++) {
if((graph[x][i] == 1) && (!visited[i]))
{
queue.add(i);
visited[i]=true;
}
}
}
//convert back to array
return output.stream().mapToInt(Integer::intValue).toArray();

/*if you can't use java 8 stream, convert output to array using:
int[] ret = new int[output.size()];
int i = 0;
for (int e : output) { ret[i++] = e; }
return ret;
*/
}

关于java - 给定图上无向图 BFS 的 “Adjacency Matrix” 表示并输出顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49843436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com