The solution is accepted but it gives wrong result for the following test cases


For the test case:
A : [ “ABCE”, “SFCS”, “ADEE” ]
B : “ABCB”

The epected answer is 0 but the solution returned 1.
int X[]={0, 0, 1, -1};
int Y[]={1, -1, 0, 0};
int n, m, l;

bool dfs(int x, int y, vector<string> &A, string B, int ind){
    `Preformatted text`if(ind==l)
        return true;
    for(int i=0;i<4;i++){
        int newx= x+X[i];
        int newy=y+Y[i];
        if(newx>=0 && newx<n && newy>=0 && newy<m && A[newx][newy]==B[ind])
            if(dfs(newx, newy, A, B, ind+1))
                return true;
    return false;
int Solution::exist(vector<string> &A, string B) {
        return 1;
    bool ans=false;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
                ans=ans | dfs(i, j, A, B, 1);
                    return 1;
    return 0;


The expected output is 1. Remember that we can use the same cell twice as long as we’re reaching that cell from its adjacent cell. We can form ABCB by traversing the first row as A->B->C->B.