Skip to content

Cycle detection in 2d array #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions CPP/array-2d/CycleDetection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// https://binarysearch.com/problems/Cycle-Detection-in-a-Matrix
// 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.

vector<vector<int>> nb = {{0,1},{0,-1},{1,0},{-1,0}};

bool helper(vector<vector<int>>& mat,int x,int y,int key,vector<vector<int>>& vis){
vis[x][y]=1;
bool ans=0;
for(int i =0; i < 4; i++){
int x1 = x+nb[i][0];
int y1 = x+nb[i][1];
if(x1 > -1 && x1 < mat.size() && y1 > -1 && y1 < mat[0].size() && mat[x1][y1]==key){
cout<<" inner loop "<<x1<<" "<<y1<<" "<<ans<<endl;
if( !vis[x1][y1]){
ans |=helper(mat,x1,y1,key,vis);
}
else if( vis[x1][y1] && (x1 != x || y1 != y)){
return true;
}
}
}
cout<<x<<" "<<y<<" "<<ans<<endl;
return ans;
}

bool solve(vector<vector<int>>& mat) {
vector<vector<int>> vis(mat.size(),vector<int>(mat[0].size(),0));
for(int i=0; i < mat.size();i++){
for(int j=0; j < mat[0].size();j++){
if(vis[i][j]==0){
if(helper(mat,i,j,mat[i][j],vis))return 1;
}
}
}
return 0;
}