gpt4 book ai didi

java - 为什么返回值不等于数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:45 25 4
gpt4 key购买 nike

我正在进行深度优先搜索,但输出不等于数组。怎么了?

public static int[] Search (int [][] graph){
boolean[] visited = {false, false, false, false, false, false};
int n = 6;
List<Integer> output = new ArrayList<>();
Search(graph, visited, n, 0);
return output.stream().mapToInt(Integer::intValue).toArray();
}

public static void Search(int[][] graph, boolean [] visited, int n, int i) {
System.out.print((i )+" ");
visited[i] = true;
for (int j = 0; j < n; j++) {
if (!(visited[j]) && graph[i][j] == 1) {
Search(graph, visited, n, j);
}
}
}

public static void main(String[] args) {

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 [] Searchresult={0,1,4,5,2,3};

}

如您所见,DFSresult 和输出是相同的。我的返回声明有误吗?

最佳答案

您的DFS(graph) 方法返回一个空数组:

List<Integer> output = new ArrayList<>();
DFS(graph, visited, n, 0);
return output.stream().mapToInt(Integer::intValue).toArray();

您永远不会向创建数组的 ArrayList 添加任何内容。

您可能忘记了将 output 列表传递给 void DFS(int[][] graph, boolean [] visited, int n, int i) 方法并为其添加值。

public static int[] DFS (int [][] graph) {
boolean[] visited = {false, false, false, false, false, false};
int n = 6;
List<Integer> output = new ArrayList<>();
DFS(graph, visited, n, 0, output);
return output.stream().mapToInt(Integer::intValue).toArray();
}

public static void DFS(int[][] graph, boolean [] visited, int n, int i, List<Integer> output) {
System.out.print((i )+" ");
output.add(i);
visited[i] = true;
for (int j = 0; j < n; j++) {
if (!(visited[j]) && graph[i][j] == 1) {
DFS(graph, visited, n, j, output);
}
}
}

进行这些更改后,输出变为

0 1 4 5 2 3 DFS is working correctly

关于java - 为什么返回值不等于数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50099806/

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