 # Help me solving tricky question

In a grid of NXN, you have to find if an element appears k times consecutively (up, down, left, right, diagonal). If yes, return the element else return -1.
If multiple elements exist, return the smallest number.
Input Specification:
input1- The value of N input, A 2-d array representing the grid (all elements ) input3: The value of k
Output Specification:
Returns the smallest element which appears k times consecutively (up. down, left, right, diagonal). If no such element exists, return -1.

Example-
input1:5
input2:
[[3,5,3,9,5],[4,3,2,1,8],[9,4,3,1,9],[8,4,7,6,4],[1,2,5,9,1]]
input3: 3

Output- 3
in this grid,3 is available for 3 times in the diagonal

Can you share the link ?

1 Like
``````int k,n;
int x=INT_MAX;
int ar={{0,1},{0,-1},{1,0},{-1,0},{1,-1},{-1,1},{1,1},{-1,-1}};
void dfs(int r,int c,int parent,int l,vector<vector<int>> arr,vector<vector<int>> &visit){
if(k==l){
x=min(x,parent);
return;
}
visit[r][c]=1;
for(int i=0;i<8;++i){
int r1=r+ar[i];
int c1=c+ar[i];
if(r1>=0 && r1<n && c1>=0 && c1<n && arr[r1][c1]==parent && visit[r1][c1]==0){
dfs(r1,c1,parent,l+1,arr,visit);
}
}
return;
}
int main(){
cin>>n>>k;
vector<vector<int>>visit(n,vector<int>(n,0));
vector<vector<int>>arr(n,vector<int>(n,0));
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cin>>arr[i][j];
}
}
dfs(0,0,arr,1,arr,visit);
cout<<x;
}
``````

dfs solution of above que