Repository navigation
Expand file tree
/
Copy pathcircular_array_loop.cpp
More file actions
102 lines (75 loc) · 2.37 KB
/
Copy pathcircular_array_loop.cpp
File metadata and controls
102 lines (75 loc) · 2.37 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<bits/stdc++.h>
using namespace std;
// class Solution {
// public:
// bool dfs(int node, vector<int>& nums, vector<vector<int>> &graph, vector<int> &visited, vector<int> stack, int direction){
// visited[node] = 1;
// stack[node] = 1;
// for(int i = 0; i < graph[0].size(); i++){
// if(node == i)
// continue;
// if(graph[node][i] == 1 && direction*nums[i] > 0 && !(visited[i] == 1)){
// if(dfs(i, nums, graph, visited, stack, direction)){
// return true;
// }
// }
// else if(graph[node][i] == 1 && (stack[i] == 1))
// return true;
// }
// return false;
// }
// bool circularArrayLoop(vector<int>& nums) {
// int n = nums.size();
// vector<vector<int>> graph(n, vector<int>(n, 0));
// vector<int> visited(n, 0), stack(n, 0);
// for(int i = 0; i < n; i++){
// int neigh = ((i+nums[i])%n+n)%n;
// graph[i][neigh] = 1;
// }
// for(int i = 0; i < n; i++){
// int direction = nums[i] < 0 ? -1 : 1;
// if(visited[i] != 1)
// if(dfs(i, nums, graph, visited, stack, direction)){
// return true;
// }
// }
// return false;
// }
// };
/*Using Union Find*/
class Solution {
public:
int find(int node, vector<int> parent){
if(parent[node] == node)
return node;
return parent[node] = find(parent[node], parent);
}
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
vector<int> parent(n, 0);
for(int i = 0; i < n; i++)
parent[i] = i;
for(int i = 0; i < n; i++){
int j = ((i + nums[i])%n+n)%n;
if(i != j && nums[i]*nums[j] > 0){
int prnt1 = find(i, parent);
int prnt2 = find(j, parent);
if(prnt1 == prnt2)
return true;
parent[prnt1] = prnt2;
}
}
return false;
}
};
int main(){
Solution* soln = new Solution();
vector<int> nums;
int n, numb;
cin>>n;
for(int i = 0; i < n; i++){
cin>>numb;
nums.push_back(numb);
}
cout<<soln->circularArrayLoop(nums);
}