forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphdfsll.java
More file actions
69 lines (65 loc) · 1.44 KB
/
Copy pathgraphdfsll.java
File metadata and controls
69 lines (65 loc) · 1.44 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.*;
class graph
{
int v;
LinkedList<Integer> adjListArray[];
graph(int v)
{
this.v=v;
adjListArray =new LinkedList[v];
for(int i=0;i<v;i++)
{
adjListArray[i]=new LinkedList<>();
}
}
void addEdge(int a,int b)
{
adjListArray[a].add(b);
adjListArray[b].add(a);//beacause undirectional graph
}
void print()
{
for(int i=0;i<v;i++)
{
System.out.println("Adjancy List of vertex:"+adjListArray[i]);
for(Integer n:adjListArray[i])
{
System.out.println(n+"");
}
}
}
void dfs(int s) //recursion happening
{
System.out.println("---------DFS----------");
boolean visited[]=new boolean[v];
DFSutil(visited,s);
}
void DFSutil(boolean visited[],int s)
{
visited[s]=true;
System.out.println(s+" ");
Iterator<Integer> it=adjListArray[s].iterator();
while(it.hasNext())
{
int n=it.next();
if(!visited[n])
{
DFSutil(visited,n);
}
}
}
}
class graphdfsqll
{
public static void main(String[] args)
{
graph g= new graph(5);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,3);
g.addEdge(3,4);
g.addEdge(4,2);
g.print();
g.dfs(0);
}
}