# 79 Word Search

## 79. [Word Search](https://leetcode.com/problems/word-search/description/)

## 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,\
Given**board**=

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

**word** =`"ABCCED"`, -> returns`true`,

**word** =`"SEE"`, -> return`true`,

**word** =`"ABCB"`, -> returns`false`.

## 2. Implementation

**(1) Backtracking**

```java
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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/backtracking/79-word-search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
