Backtracking Problem (Need Help)

I was trying to solve a problem using recursion in which i have to find min steps to reach from source to destination although this question had pretty simple observation but i just want to know how can i fix my recursive code as its going to infinite loop.

LINK:

My Code:

#include<bits/stdc++.h>
using namespace std;

const int D=10;

int minSteps(int board[D][D],int r,int c,int curR,int curC,int desR,int desC){
cout<<curR<<" "<<curC<<endl;
if(curR<0 || curR>=r || curC<0 || curC>=c){
// cout<<"I am here "<<endl;
return INT_MAX;
}
if((curR == desR) && (curC == desC)){
return 1;
}
int left = minSteps(board, r, c, curR, curC-1, desR, desC) + 1;
int right = minSteps(board, r, c, curR, curC+1, desR, desC) + 1;
int up = minSteps(board, r, c, curR-1, curC, desR, desC) + 1;
int down = minSteps(board, r, c, curR+1, curC, desR, desC) + 1;

return min(left,min(right,min(up,down)));

}

int main(){

int r,c; cin>>r>>c;
int arr[D][D] = {0};
int sr,sc,dr,dc;

for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cin>>arr[i][j];
if(arr[i][j] == 1){
sr=i;
sc=j;
}
if(arr[i][j] == 2){
dr=i;
dc=j;
}
}
}
//cout<<sr<<" “<<sc<<” “<<dr<<” "<<dc<<endl;
int ans = minSteps(arr, r, c, sr, sc, dr, dc);
cout<<ans<<endl;

return 0;
}

Since you are visiting in all the directions each time, the node from where you started or already considered for that particular path will be traversed again and this will keep repeating and hence fall into an infinite recursion case. In order to solve this problem you’ll need to consider a boolean array for path and need to backtrack it each time.

@silvester14 Ok bro i got it , but i followed the same concept that of finding min cost path problem
Min Cost Path | DP-6 - GeeksforGeeks

could you help me with its implementation as i am practicing backtracking it will help me alot.

Can anyone help me with implementation please… :grimacing: