# 79. Word Search (Backtracking)

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

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.
```

***My Solutions:***

用backtracking/dfs的思想

同一个char不能用两次，所以先把当前char标记为\*，dfs结束后再还原

```
class Solution {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (helper(board, word, i, j, 0)) return true;
            }
        }
        return false;
    }
    
    private boolean helper(char[][] board, String word, int i, int j, int index) {
        
        if (index >= word.length()) return true;
        
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
        
        if (word.charAt(index) != board[i][j]) return false;
            
        index++;
        char c = board[i][j];
        board[i][j] = '*';
        boolean res = helper(board, word, i + 1, j, index) 
            || helper(board, word, i - 1, j, index) 
            || helper(board, word, i, j + 1, index) 
            || helper(board, word, i, j - 1, index);
        
        board[i][j] = c; // restore this cell
        return res;
    }
}
```

>
