# 79.Word-Search

## 79. Word Search

## 题目地址

<https://leetcode.com/problems/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.
```

## 代码

### Approach 1: Backtracking

```java
class Solution {
  private char[][] board;
  private int ROWS;
  private int COLS;

  public boolean exist(char[][] board, String word) {
    this.board = board;
    this.ROWS = board.length;
    this.COLS = board[0].length;

    for (int row = 0; row < this.ROWS; row++) {
      for (int col = 0; col < this.COLS; col++) {
        if (backtrack(row, col, word, 0)) { // match the first letter
          return true;
        }
      }
    }
    return false;
  }

  private boolean backtrack(int row, int col, String word, int index) {
    if (index >= word.length()) {
      return true;
    }

    if (row < 0 || row == this.ROWS || col < 0 || col == this.COLS || this.board[row][col] != word.charAt(index)) {
         return false;
    }

    boolean ret = false;
    this.board[row][col] = '#'; // 防止回溯

    int[] rowOffsets = {0, 1, 0, -1};
    int[] colOffsets = {1, 0, -1, 0};
    for (int d = 0; d < 4; d++) {
      int r = row + rowOffsets[d];
      int c = col + cofOffsets[d];
      ret = backtrack(r, c, word, index + 1);
      if (ret) {
        break;
      }
    }

    this.board[row][col] = word.charAt(index); // 修改回来
    return ret;
  }

}
```


---

# 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://wentao-shao.gitbook.io/leetcode/graph-search/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.
