From 2b3beeedd14d6f966103d96e0c6366bf1c12a7bc Mon Sep 17 00:00:00 2001 From: Eswari-Priya Date: Sun, 2 Oct 2022 02:00:42 +0530 Subject: [PATCH] Cycle detection in 2d array --- CPP/array-2d/CycleDetection.cpp | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 CPP/array-2d/CycleDetection.cpp diff --git a/CPP/array-2d/CycleDetection.cpp b/CPP/array-2d/CycleDetection.cpp new file mode 100644 index 00000000..045fcded --- /dev/null +++ b/CPP/array-2d/CycleDetection.cpp @@ -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> nb = {{0,1},{0,-1},{1,0},{-1,0}}; + +bool helper(vector>& mat,int x,int y,int key,vector>& 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 "<>& mat) { + vector> vis(mat.size(),vector(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; +} \ No newline at end of file