Skip to content

Commit 5e21866

Browse files
Merge pull request #102 from Eswari-Priya/Cycle
Cycle detection in 2d array
2 parents ace2fea + 2b3beee commit 5e21866

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

CPP/array-2d/CycleDetection.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// https://binarysearch.com/problems/Cycle-Detection-in-a-Matrix
2+
// You are given a two-dimensional list of integers matrix. Return whether you can start from some cell, move adjacent to neighboring cells (up, down, left, right) of the same value, and come back to the same starting cell. You can’t revisit a cell you last visited.
3+
4+
vector<vector<int>> nb = {{0,1},{0,-1},{1,0},{-1,0}};
5+
6+
bool helper(vector<vector<int>>& mat,int x,int y,int key,vector<vector<int>>& vis){
7+
vis[x][y]=1;
8+
bool ans=0;
9+
for(int i =0; i < 4; i++){
10+
int x1 = x+nb[i][0];
11+
int y1 = x+nb[i][1];
12+
if(x1 > -1 && x1 < mat.size() && y1 > -1 && y1 < mat[0].size() && mat[x1][y1]==key){
13+
cout<<" inner loop "<<x1<<" "<<y1<<" "<<ans<<endl;
14+
if( !vis[x1][y1]){
15+
ans |=helper(mat,x1,y1,key,vis);
16+
}
17+
else if( vis[x1][y1] && (x1 != x || y1 != y)){
18+
return true;
19+
}
20+
}
21+
}
22+
cout<<x<<" "<<y<<" "<<ans<<endl;
23+
return ans;
24+
}
25+
26+
bool solve(vector<vector<int>>& mat) {
27+
vector<vector<int>> vis(mat.size(),vector<int>(mat[0].size(),0));
28+
for(int i=0; i < mat.size();i++){
29+
for(int j=0; j < mat[0].size();j++){
30+
if(vis[i][j]==0){
31+
if(helper(mat,i,j,mat[i][j],vis))return 1;
32+
}
33+
}
34+
}
35+
return 0;
36+
}

0 commit comments

Comments
 (0)