class Solution {
public:
bool search(vector<vector<char>>& board, string word,int wi,int row,int col){
// visited[row][col]=1;
char c=board[row][col];
board[row][col]=' ';
int n=board.size(),m=board[0].size();
//Base Case
int ws=word.length()-1;
if(wi==ws && word[wi]==c){
return true;
}
if(word[wi]!=c){
board[row][col]=c;
return false;
}
cout<<"matched "<<word[wi]<<"\n";
int dx[4]={0,0,1,-1};
int dy[4]={-1,1,0,0};
int nx,ny;
bool found;
for(int i=0;i<4;i++){
nx=row+dx[i];
ny=col+dy[i];
if(nx<0 or nx>=n or ny<0 or ny>=m or board[nx][ny]==' ' or word[wi+1]!=board[nx][ny]) continue;
cout<<"searching "<<nx<<" "<<ny<<"\n";
found=search(board,word,wi+1,nx,ny);
cout<<"found "<<found<<"\n";
if(found){
return true;
}
}
board[row][col]=c;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int n=board.size(),m=board[0].size();
// vector<vector<int>> visited(n,vector<int> (m,-1));
bool found=false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]==word[0]){
found=search(board,word,0,i,j);
if(found){
return true;
}
}
}
}
return false;
}
};
Can anyone Please Explain Why I am Getting TLE and how to avoid it.Because the approach others using are also similar so no not able to get it Why I am getting TLE.