79 Word Search

1. Question

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example, Givenboard=

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word ="ABCCED", -> returnstrue,

word ="SEE", -> returntrue,

word ="ABCB", -> returnsfalse.

2. Implementation

(1) Backtracking

class Solution {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || word == null || word.length() == 0) {
            return false;
        }

        int m = board.length, n = board[0].length;
        boolean[][] visited = new boolean[m][n];

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (searchWord(0, i, j, word, directions, visited, board)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean searchWord(int index, int row, int col, String word, int[][] directions, boolean[][] visited, char[][] board) {
        if (index == word.length()) {
            return true;
        }

        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != word.charAt(index) || visited[row][col]) {
            return false;
        }

        visited[row][col] = true;
        for (int[] direction : directions) {
            int nextRow = row + direction[0];
            int nextCol = col + direction[1];

            if (searchWord(index + 1, nextRow, nextCol, word, directions, visited, board)) {
                return true;
            }
        }
        visited[row][col] = false;
        return false;
    }
}

3. Time & Space Complexity

时间复杂度O(mn*4^L),m为board的行数,n为board的列数,L为word的长度, 空间复杂度O(mn)

Last updated