Can someone please let me know why my code fails for half of the test cases.


  • 0
    M
    public class Solution {
    public boolean exist(char[][] board, String word) {
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < board.length;++i) {
        for(int j = 0; j < board[0].length;++j) {
            char ch = board[i][j];
            if(existsUtil(board, i, j, word,sb)) {
                return true;
            }
        }
    }
    return false;
    

    }

       public boolean existsUtil(char[][] board,int i,int j,String word, StringBuilder builder) {
        
        if (i < 0 || j < 0 || i == board.length || j == board[0].length) {
            return false;
        }
        
        if (!word.startsWith(builder.toString())) {
            return false;
        }
        
        if(builder.toString() == word){
            return true;
        }
        builder.append(board[i][j]);
        existsUtil(board, i, j + 1, word,builder);
        existsUtil(board, i, j - 1, word,builder);
        existsUtil(board, i - 1, j, word,builder);
        existsUtil(board, i + 1, j, word,builder);
      
        return false;  
    }
    

    }


Log in to reply
 

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