面试题 04.01. 节点间通路-----DFS、BFS
作者:互联网
题目表述
节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
示例:
输入: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出: true
DFS、BFS
-
根据graph构建邻接表,可以用map构建,也可以用List构建。
-
BFS: 创建队列que存放当前节点以及访问过但未扩展的节点,用visited[]数组记录已经访问过的节点。
-
DFS: 用visited[]数组记录已经访问过的节点,迭代每条路径深度搜索,一旦找到target返回true
bfs
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
List<List<Integer>> graphlist = new ArrayList<>();
for(int i= 0; i < n;i++){
graphlist.add(new ArrayList<>());
}
for(int[] tmp : graph){
graphlist.get(tmp[0]).add(tmp[1]);
}
boolean[] visited = new boolean[n];
return bfs(graphlist,start,target,visited);
}
public boolean bfs(List<List<Integer>> graph, int start, int target, boolean[] visited){
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
visited[start] = true;
while (!queue.isEmpty()){
int tmp = queue.poll();
if(tmp == target){
return true;
}
for(int i : graph.get(tmp)){
if(visited[i]) continue;
queue.offer(i);
visited[i] = true;
}
}
return false;
}
}
dfs
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
List<List<Integer>> graphlist = new ArrayList<>();
for(int i= 0; i < n;i++){
graphlist.add(new ArrayList<>());
}
for(int[] tmp : graph){
graphlist.get(tmp[0]).add(tmp[1]);
}
boolean[] visited = new boolean[n];
return dfs(graphlist,start,target,visited);
}
public boolean dfs(List<List<Integer>> graph, int start, int target, boolean[] visited){
visited[start] = true;
if(start == target){
return true;
}
for(int i : graph.get(start)){
if(visited[i]) continue;
if (dfs(graph,i,target,visited)) return true;
}
return false;
}
}
标签:面试题,target,int,graph,DFS,BFS,start,boolean,visited 来源: https://www.cnblogs.com/youngerwb/p/16244507.html