Why TLE in this simple BFS approach?


#1
int dfs(int i,int j, int pos, const string &b, const vector<string> &a){
    if(pos == b.size()-1) return 1;
    
    int r[4] = {-1, 0, 1, 0};
    int c[4] = {0, 1, 0, -1};
    int n = a.size(), m = a[0].size();
    
    for(int k=0;k<4;k++){
        int i1 = i + r[k], j1 = j + c[k];
        if(i1 >= 0 && i1<n && j1>=0 && j1<m && a[i1][j1] == b[pos+1]){
            return dfs(i1, j1, pos+1, b, a);
        }
    }
    return 0;
}

int Solution::exist(vector<string> &a, string b) {
    for(int i=0;i<a.size();i++){
        for(int j=0;j<a[0].size();j++){
            if(a[i][j] == b[0]){
                if(dfs(i,j,0,b,a)) return 1;
            }
        }
    }
    return 0;
}