-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDFS_Graph.java
More file actions
27 lines (24 loc) · 775 Bytes
/
DFS_Graph.java
File metadata and controls
27 lines (24 loc) · 775 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
// Function to return a list containing the DFS traversal of the graph.
public ArrayList<Integer> dfsOfGraph(ArrayList<ArrayList<Integer>> adj) {
ArrayList<Integer> ls= new ArrayList<>();
int c=0;
for(ArrayList<Integer> sublist : adj){
if(!sublist.isEmpty()){
c++;
}
}
boolean vis[]= new boolean[c+1];
dfs(0,vis,adj,ls);
return ls;
}
public static void dfs(int node, boolean vis[], ArrayList<ArrayList<Integer>> adj, ArrayList<Integer> ls){
vis[node]=true;
ls.add(node);
for(Integer it: adj.get(node)){
if(vis[it]==false){
dfs(it,vis,adj,ls);
}
}
}
}