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:

https://www.codechef.com/KQ152019/problems/KQM15A

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;

}