8ms beats 96.13 % Java Solution Easy To understand


  • 1
    K
    public class Solution {
        public boolean exist(char[][] board, String words) {
            char[] word = words.toCharArray();
            for(int i = 0; i<board.length;i++){
                for(int j = 0; j<board[0].length;j++){
                    if(board[i][j] == word[0]){
                        if(helper(board, i, j, word,0)){return true;}
                    }
                }//for j
            }//for i
            return false;
        }//exist
        
        public boolean helper(char[][] board, int i, int j, char[] word,int index){
            if(index == word.length)return true;
            if(i<0 || j<0 || i == board.length || j == board[i].length) return false;
            if(board[i][j] != word[index])return false;
            
            board[i][j] ^= 256;
            
            boolean exist = helper(board, i, j+1, word, index+1) 
            || helper(board, i-1, j, word, index+1)
            || helper(board, i, j-1, word, index+1)
            || helper(board, i+1, j, word, index+1);
            
            board[i][j] ^= 256;
            return exist;
        }//helper
    }

Log in to reply
 

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