我正在进行深度优先搜索,但输出不等于数组。有什么问题?
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和输出相同。我在退货声明中犯了错误吗?
答案 0 :(得分:3)
您的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正常工作