Recursive JS solution


  • 0
    R
    var exist = function(board, word) {
        for(var i = 0; i < board.length; i++) {
            for(var j = 0; j < board[0].length; j++) {
                if(existRec(board,word,i,j,{}))
                    return true;
            }
        }
        return false;
    };
    
    function existRec(board,word,y,x,history) {
        if(word.length === 0) 
            return true;
        else if(board[y][x] === word.substring(0,1)){
            word = word.substring(1,word.length);
            if( word.length === 0)
                return true;
            history[y + " " + x] = true;
            if ((y > 0 && history[(y-1) + " " + x] === undefined && existRec(board,word,y-1,x,history)) ||
            (y < board.length-1 && history[(y+1) + " " + x] === undefined && existRec(board,word,y+1,x,history)) ||
            (x > 0 && history[y + " " + (x-1)] === undefined && existRec(board,word,y,x-1,history)) ||
            (x < board[y].length-1 && history[y + " " + (x+1)] === undefined && existRec(board,word,y,x+1,history)))
                return true;
            else
                delete history[y + " " + x];
        }
        else 
            return false;
    }

Log in to reply
 

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