billy_don
Senior Member
Toàn bài easy post lên tốn tiền net@billy_don bữa nay chưa thấy bác trả bài
Java:
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
List<Integer>[] graph = new List[n];
for (int[] edge: edges) {
if (graph[edge[0]] == null) graph[edge[0]] = new ArrayList<>();
if (graph[edge[1]] == null) graph[edge[1]] = new ArrayList<>();
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
boolean[] visited = new boolean[n];
return dfs(source, visited, graph, destination);
}
private boolean dfs(int source, boolean[] visited, List<Integer>[] graph,int destination) {
if (source == destination) {
return true;
}
visited[source] = true;
for (int next: graph[source]) {
if (!visited[next]) {
if (dfs(next, visited, graph, destination)) {
return true;
}
}
}
return false;
}
}