It will take few second to understand my simple backtracking code, Can anyone please tell me why I am getting WA.


  • 0
    A

    class Solution {
    int e[4]={1,-1,0,0};
    int f[4]={0,0,1,-1};
    int wl,row,col;
    bool check(vector<vector<char> >& board, string word,int i,int j,int pos)
    {

        if((i>row-1 || i<0) || (j>col-1 || j<0) || pos>=wl){//cout<<"fuck\n";
        return false;}
    
        if(pos==wl-1 && word[pos]==board[i][j])return true;//if last char match return true
    
        char c=board[i][j];
        board[i][j]='*';
    
        if(word[pos]==c){//cout<<"again\n";
        for(int i1=0;i1<4;i1++)
        {
            if(check(board,word,i+e[i1],j+f[i1],pos+1))return true;
        }
        }
        board[i][j]=c;
        
        return false;
    }
    

    public:
    bool exist(vector<vector<char> >& board, string word) {

         row=board.size();
         col=board.size();
        wl=word.size();
        for(int a=0;a<row;a++){
            for(int b=0;b<col;b++){
                if(board[a][b]==word[0])
                {
                    if(check(board,word,a,b,0))return true;
                }
            }
        }
    
        return false;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.