Skip to content

Latest commit

 

History

History
40 lines (39 loc) · 1.39 KB

0079. Word Search.md

File metadata and controls

40 lines (39 loc) · 1.39 KB

Solution1

class Solution {
    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() == 0) {
            return false;
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, visited, word, 0, i, j)) {
                    return true;
                } 
            }
        }
        return false;
    }
    private boolean dfs(char[][] board, boolean[][] visited, String word, int index, int row, int col) {
        if (index == word.length()) {
            return true;
        }
        if (row >= 0 && col >= 0 && row < board.length && col < board[0].length 
            && !visited[row][col] && board[row][col] == word.charAt(index)) {
            visited[row][col] = true;
            if (dfs(board, visited, word, index + 1, row + 1, col) ||
                dfs(board, visited, word, index + 1, row - 1, col) ||
                dfs(board, visited, word, index + 1, row, col + 1) ||
                dfs(board, visited, word, index + 1, row, col - 1)) {
                return true;
            }
            visited[row][col] = false;
        }
        return false;
    }
}

note

  • dfs. Remember to backtrack (change the visited to false after recursive calls)
  • Time O(n^2 * 3^word.length())