-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPath Exist or Not
63 lines (60 loc) · 1.58 KB
/
Path Exist or Not
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
import java.util.*;
public class Path {
static void dfs(ArrayList<ArrayList<Integer>> adj,int source, int destination,boolean[] vis)
{
vis[source]=true;
for(int j:adj.get(source)) {
if(!vis[j])
{
dfs(adj,j,destination,vis);
}
}
}
static boolean findPath(ArrayList<ArrayList<Integer>> adj,int source,int destination)
{
boolean[] vis = new boolean[6];
for(int i=0;i<5;i++)
{
vis[source]=true;
if(source==destination)
return true;
if(!vis[i])
{
dfs(adj,i,destination,vis);
}
}
return false;
}
public static void main(String arg[])
{
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
for(int i=0;i<5;i++)
{
adj.add(new ArrayList<>());
}
adj.get(0).add(1);
adj.get(0).add(2);
adj.get(1).add(0);
adj.get(1).add(2);
adj.get(1).add(3);
adj.get(1).add(4);
adj.get(2).add(0);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(3).add(1);
adj.get(3).add(2);
adj.get(3).add(4);
adj.get(4).add(1);
adj.get(4).add(3);
System.out.println(adj);
int source = 0;
int destination = 4;
boolean ans = findPath(adj,source,destination);
if(ans)
{
System.out.println("path exist");
}
else
System.out.println("no such path exist");
}
}