Simple Java Solution


  • 0
    A
    public class Solution {
        public boolean exist(char[][] board, String word) {
            if (word == null){
                return true;
            }
            for (int i = 0; i < board.length; i++){
                for (int j = 0; j < board[0].length; j++){
                    if (board[i][j] == word.charAt(0) && searchWord(i,j,word,board,0,new boolean[board.length][board[0].length])){
                        return true;
                    }
                }
            }
            return false;
        }
        
        public boolean searchWord (int i, int j, String s, char[][] board, int k,boolean[][] isVisited){
            if (k == s.length()){
                return true;
            }
            if (i < 0 || j < 0 || i > board.length - 1 || j > board[0].length - 1 || k > s.length() - 1 || isVisited[i][j] || board[i][j] != s.charAt(k)){
                return false;
            }
            
            isVisited[i][j] = true;
            if(searchWord(i+1,j,s,board,k+1,isVisited)){
                return true;
            }
            if (searchWord(i,j+1,s,board,k+1,isVisited)){
                return true;   
            }
            if (searchWord(i-1,j,s,board,k+1,isVisited)){
                return true;    
            }
            if (searchWord(i,j-1,s,board,k+1,isVisited)){
                return true;    
            }
            isVisited[i][j] = false;
            return false;
        }
    }

Log in to reply
 

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