Wrong Answer please help (73/83 cases pass)


  • 0
    T

    class Solution {

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

        if(!word.size() && !board.size() && !board[0].size())
            return false;
        int m = board.size(),n = board[0].size();
        int index = 0;
        for(int i = 0;i < board.size();i++)
        {
            for(int j = 0;j < board[i].size();j++)
            {
                if(DFS(board,i,j,word,index,m,n) == true)
                    return true;
            }
        }
        return false;
    }
    

    private:

    bool DFS(vector<vector<char>>& board,int i,int j,string word,int index,int row,int col)
    {
        if(i < 0 || j < 0 || i >= row || j >= col)
            return false;
        if(board[i][j] != word[index])
            return false;
        if(index == word.size()-1)
            return true;
            
        if(DFS(board,i,j+1,word,index+1,row,col))
            return true;
        if(DFS(board,i,j-1,word,index+1,row,col))
            return true;
        if(DFS(board,i+1,j,word,index+1,row,col))
            return true;
        if(DFS(board,i-1,j,word,index+1,row,col))
            return true;
        
        return false;
    }
    

    };


  • 0
    T

    took a visited array and it worked...no worries now ... :)


Log in to reply
 

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