Java Solution: 9 MS


  • 0
    S
    public class Solution {
        public boolean exist(char[][] board, String word) {
            if(board.length==1){
                System.out.println("right");
            }
            char[] wordArray=word.toCharArray();
            return helper(board,wordArray,0,0,0);
        }
        
        public boolean helper(char[][] board, char[] wordArray, int index, int row, int column){
            //base case
            if(index>=wordArray.length) return true;
            char lookingFor=wordArray[index];
            if(index==0){
                for(int i=row;i<board.length;i++){
                    for(int j=column;j<board[0].length;j++){
                        if(board[i][j]==lookingFor){
                            board[i][j]='%';
                            if(helper(board,wordArray,index+1,i,j)){return true;}
                            board[i][j]=lookingFor;
                            
                        }
                    }
                }
                return false;
            }else{
               
                //search left
               
                if(column-1>=0 && board[row][column-1]==lookingFor){
                    board[row][column-1]='%';
                    if(helper(board,wordArray,index+1,row,column-1)) return true;
                     board[row][column-1]=lookingFor;
                }
                
                
                //search top
                  
                if(row-1>=0 && board[row-1][column]==lookingFor){
                     board[row-1][column]='%';
                    if(helper(board,wordArray,index+1,row-1,column)) return true;
                     board[row-1][column]=lookingFor;
                }
                 
                
                //search right
                
                 
                if(column+1<board[0].length && board[row][column+1]==lookingFor){
                     board[row][column+1]='%';
                    if(helper(board,wordArray,index+1,row,column+1)) return true;
                    board[row][column+1]=lookingFor;
                }
                 
                
                //search bottom
                 
                if(row+1<board.length && board[row+1][column]==lookingFor){
                     board[row+1][column]='%';
                    if(helper(board,wordArray,index+1,row+1,column)) return true;
                    board[row+1][column]=lookingFor;
                }
                  
                return false;
            }
            
        }
    }
    

Log in to reply
 

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