public class DFS {
boolean[] visited = new boolean[5];
public DFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<4;i++){
adj.add(new ArrayList<>());
}
DFS g = new DFS();
g.addEdge(adj,0, 1);
g.addEdge(adj,0, 2);
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 0);
g.addEdge(adj,2, 3);
g.addEdge(adj,3, 3);
g.DFS(2,adj);
}
void DFS(int v,ArrayList<ArrayList<Integer>> adj){
visited[v]=true;
System.out.println(v);
ArrayList<Integer> list = adj.get(v);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
DFS(i,adj);
}
}
}
}
boolean[] visited = new boolean[5];
public DFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<4;i++){
adj.add(new ArrayList<>());
}
DFS g = new DFS();
g.addEdge(adj,0, 1);
g.addEdge(adj,0, 2);
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 0);
g.addEdge(adj,2, 3);
g.addEdge(adj,3, 3);
g.DFS(2,adj);
}
void DFS(int v,ArrayList<ArrayList<Integer>> adj){
visited[v]=true;
System.out.println(v);
ArrayList<Integer> list = adj.get(v);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
DFS(i,adj);
}
}
}
}
No comments:
Post a Comment