My accepted DFS java solution


  • 0
    R

    I had hard time keeping track of indexes with other java solutions and I finally was able simply my solution using DFS

    enter code here public class Solution {
    public boolean exist(char[][] board, String word) {
        int lenX = board.length;
        int lenY = board[0].length;
        boolean result = false;
        boolean [][] used = new boolean [lenX][lenY];
    
        for (int i = 0; i < lenX; i++) {
            for (int j = 0; j < lenY; j++) {
                if (board[i][j] == word.charAt(0)) {
                    result = searchNext(board, used, 0, word, i, j);
                    if(result == true) {
                        return true;
                    }
                }
            }
        }
    
        return false;
    }
    
    public boolean searchNext(char[][] board, boolean [][] used, int chAt,
            String word, int x, int y) {
    
        boolean result = false;
        if (chAt == word.length()) {
            return true;
        }
        if (y < 0 || x < 0 || y >= board[0].length || x >= board.length) {
            return false;
        }
        
        
        if (!used[x][y] && board[x][y] == word.charAt(chAt)) {
            used[x][y] = true;
            
            if (searchNext(board, used, chAt + 1, word, x, y - 1)) {
                return true;
            }
        
            if (searchNext(board, used, chAt + 1, word, x, y + 1)) {
                return true;
            }
        
            if (searchNext(board, used, chAt + 1, word, x - 1, y)) {
                return true;
            }
        
            if (searchNext(board, used, chAt + 1, word, x + 1, y)) {
                return true;
            }
            used[x][y] = false;
        }
        
        return false;
    }
    

    }


Log in to reply
 

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