Partially Correct Answer. How can this be memoized?


#1
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};

int func(vector<string> A, string B, int i, int j, int index ){
int res=0;
if(A[i][j]!=B[index])
    return 0;
if(B.size()==index+1)
    return 1;
for(int k=0;k<4;++k){
    if(i+dx[k]<0 || j+dy[k]<0 || i+dx[k]>=A.size() || j+dy[k]>=A[0].size())
        continue;
    if(A[i+dx[k]][j+dy[k]] == B[index+1]){
        res=func(A,B,i+dx[k],j+dy[k], index+1);
    }
}
return res;
}

int Solution::exist(vector<string> &A, string B) {
int res=0, m, n, i, j;
m=A.size();
n=A[0].size();
for(i=0;i<m;++i){
    for(j=0;j<n;++j){
        res=func(A,B,i,j,0);
        if(res==1)
            return res;
    }
}
return res;
}

#2

If you know python then this is how it can be memoized