> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/exhaustive-search/word-search.md).

# 79. Word Search

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.

**Example:**

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

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
```

**Constraints:**

* `board` and `word` consists only of lowercase and uppercase English letters.
* `1 <= board.length <= 200`
* `1 <= board[i].length <= 200`
* `1 <= word.length <= 10^3`

## Thoughts

矩阵中是否出现了给定单词，一个字符只能计入一次。依次遍历矩阵中所有可能的路径=> DFS。配合标记防止走回头路。

## Code

```java
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        M, N = len(board), len(board[0])
        dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        def dfs(board, r, c, word, i):
            if i == len(word): return True
            if r < 0 or r == M or c < 0 or c == N or board[r][c] != word[i]: return False
            tmp, board[r][c] = board[r][c], ''
            for (dr, dc) in dirs:
                if dfs(board, r + dr, c + dc, word, i + 1): 
                    return True
            board[r][c] = tmp
            return False
        for r in range(M):
            for c in range(N):
                if dfs(board, r, c, word, 0):
                    print(r, c)
                    return True
        return False
            
```

```cpp
/*
 * @lc app=leetcode id=79 lang=cpp
 *
 * [79] Word Search
 */

// @lc code=start
class Solution {
public:
    vector<vector<int>> dirs{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    bool dfs(vector<vector<char>> &board, string &word, int pos, int i, int j, unordered_set<int> &visited) {
        if (word[pos] != board[i][j]) return false;
        for (const auto &d : dirs) {
            int r = i + d[0], c = j + d[1];
            if (r >= 0 && r < board.size() && c >= 0 && c < board[0].size() && !visited.count(r * board[0].size() + c)) {
                visited.insert(r * board[0].size() + c);
                if (dfs(board, word, pos + 1, r, c, visited)) return true;
                visited.erase(r * board[0].size() + c);
            }
        }
        return pos == word.size() - 1;
    }

    bool exist(vector<vector<char>>& board, string word) {
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[0].size(); ++j) {
                unordered_set<int> visited;
                visited.insert(i * board[0].size() + j);
                if (dfs(board, word, 0, i, j, visited)) return true;
            }
        }
        return false;
    }
};
// @lc code=end


```

```java
class Solution {
    int[][] dirs = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};

    private boolean helper(char[][] board, String word, int index, int x, int y) {
        if (index == word.length() - 1) {
            if (word.charAt(index) == board[x][y]) {
                return true;
            } else {
                return false;
            }
        } else if (board[x][y] != word.charAt(index)) {
            return false;
        }
        board[x][y] ^= 256;
        for (int[] dir : dirs) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length) {
                //System.out.println(Integer.toBinaryString(board[x][y]) + ", " + Integer.toBinaryString(256));
                if (helper(board, word, index + 1, nx, ny)) {
                    return true;
                }
                //System.out.println(Integer.toBinaryString(board[x][y]));
            }
        }
        board[x][y] ^= 256;
        return false;
    }

    public boolean exist(char[][] board, String word) {
        if (word.length() == 0) {
            return true;
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (helper(board, word, 0, i, j)) {
                    return true;
                }
            }
        }

        return false;
    }
}
```

## Analysis

时间复杂度参照m\_rao的分析"\
I think the time complexity is (mn\_4^k) where k is the length of the string; mn for for loop and for the dfs method its 4^k. Since the dfs method goes only as deep as the word length we have T(k)=4(T(k-1))=4\_4T(k-2)=....=.. which will be 4^k."


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://hao-fu-1.gitbook.io/oj/exhaustive-search/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.
