-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindLoops.java
More file actions
71 lines (48 loc) · 1.76 KB
/
FindLoops.java
File metadata and controls
71 lines (48 loc) · 1.76 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
70
71
import java.util.*;
import java.io.*;
/// Find if a graph contains any Cycles/Loops.
public class FindLoops {
static int N=10005;
static int[][] graph = new int[N][N];
/// A Hashmap Keep track of parent and child vertex in current iteration
static HashMap<Integer, Integer> track = new HashMap<>();
static boolean dfs(int parent, int child, int size){
/// If hashmap contains a parent that is the child node in the current iteration
/// then the graph contains a cycle.
if(track.containsKey(child)) return true;
track.put(parent, child);
boolean check = false;
for(int i=0; i<size; i++){
if(graph[child][i] == 0) continue;
check = dfs(child, i, size); /// Child becomes the parent for next iteration
}
return check;
}
static boolean hasLoops(int[][] graph, int size){
boolean flag = false;
track.clear();
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
if (graph[i][j] != 0){
flag = dfs(i, j, size);
track.clear(); /// Clear the hashmap after every iteration
}
if(flag) break;
}
}
return flag;
}
public static void main(String[] args) throws IOException {
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
int i,j,n;
n = Integer.parseInt(infile.readLine());
for(i=0; i<n; i++){
String[] inp = infile.readLine().split(" ");
for(j=0; j<n; j++){
graph[i][j] = Integer.parseInt(inp[j]);
}
}
System.out.println(hasLoops(graph, n));
infile.close();
}
}