Java solution using recursion


  • 0
    S
        public boolean exist(char[][] board, String word) {
            char firstLetter = word.charAt(0);
            for(int i=0;i<board.length;i++){
                for(int j=0;j<board[0].length;j++){
                    if(board[i][j]==firstLetter){
                        if(check(board,i,j,word))
                            return true;
                    }
                }
            }
            return false;
        }
        
        public boolean check(char[][] board, int i,int j,String word){
                int k=0;
                char[][] boardCopy=new char[board.length][board[0].length];
                for (int x = 0; x < board.length; x++) {
                	boardCopy[x] = Arrays.copyOf(board[x], board[x].length);
                	}
            if(i>boardCopy.length-1||j>boardCopy[0].length-1||i<0||j<0){
                return false;
            }
            if(word.length()==1 && boardCopy[i][j]==word.charAt(k))
                return true;
            boolean result=false;
            if(boardCopy[i][j]==word.charAt(k)){
            	boardCopy[i][j]='\0';
              result = result||check(boardCopy,i+1,j,word.substring(k+1))||check(boardCopy,i,j+1,word.substring(k+1))
                ||check(boardCopy,i,j-1,word.substring(k+1))||check(boardCopy,i-1,j,word.substring(k+1));
                   
            }else{
            return false;
        }
            return result;
        }
    }```

Log in to reply
 

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