图论-DFS路径(点与点之间的路径问题DFS)
解决问题:
点与点之间存在多少条路径?
主要思路:
DFS: 深搜,主要思想是每一次搜索时,向(当前)未访问过的子节点搜索
代码实现
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class FindPath {
// 1. 根据题意构建邻接表table
Map<Integer, int[]> table = new HashMap<>();
List<List<Integer>> res = new LinkedList<>();
Deque<Integer> path = new LinkedList<>();
// 示例数据
int[][] graph = new int[][]{{1, 2}, {3, 4, 0}, {0, 5, 6}, {1, 7}, {1, 7}, {2, 6}, {2, 5}, {3, 4}};
public int findPath(int start, int end) {
init(graph);
boolean[] visited = new boolean[table.size()];
dsf(start, end, visited);
return res.size();
}
private void dsf(int start, int end, boolean[] visited) {
path.add(start);
visited[start]=true;
if (start == end) { // 搜索到终点,记录
res.add(new LinkedList<>(path));
}
int[] sons = table.get(start);
for (int son : sons) {
if (!visited[son])
{
dsf(son, end, visited);
}
}
path.removeLast();
visited[start] = false;
}
public void init(int[][] graph) {
int v = 0;
for (int[] sons : graph) {
table.put(v, sons);
v++;
}
}
public static void main(String[] args) {
FindPath path = new FindPath();
System.out.println("path.findPath(3, 6) = " + path.findPath(3, 6));
for (List<Integer> path_ : path.res) {
System.out.println(path_);
}
}
}