题目 
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。

示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true1
2
2
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false1
2
2
提示:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15board和word仅由大小写英文字母组成
注意: 本题与主站 79 题相同:https://leetcode-cn.com/problems/word-search/
题解 
java
public boolean exist(char[][] board, String word) {
    int rows = board.length, columns = board[0].length, len = word.length();
    // 访问过的路径
    boolean[][] visited = new boolean[rows][columns];
    TrFunction<Integer, Integer, Integer, Boolean> backtrack = new TrFunction<Integer, Integer, Integer, Boolean>() {
        @Override
        public Boolean apply(Integer row, Integer column, Integer index) {
            // 已经匹配最后一个字符
            if (index == len) {
                return true;
            }
            // 越界或者已经访问过或者字符不匹配
            if (row < 0 || row >= rows
                || column < 0 || column >= columns
                || visited[row][column]
                || board[row][column] != word.charAt(index)) {
                return false;
            }
            visited[row][column] = true;
            // 继续匹配下一个字符
            if (this.apply(row + 1, column, index + 1)
                || this.apply(row, column + 1, index + 1)
                || this.apply(row - 1, column, index + 1)
                || this.apply(row, column - 1, index + 1)) {
                return true;
            }
            // 回溯
            visited[row][column] = false;
            return false;
        }
    };
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            if (backtrack.apply(i, j, 0)) {
                return true;
            }
        }
    }
    return false;
}
interface TrFunction<P1, P2, P3, R> {
    R apply(P1 p1, P2 p2, P3 p3);
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50