# 剑指 Offer 12. 矩阵中的路径

## 2. 示例

```输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"

```输入：board = [["a","b"],["c","d"]], word = "abcd"

```1 <= board.length <= 200
1 <= board[i].length <= 200
board 和 word 仅由大小写英文字母组成```

## 3. 题解

1. 起点是什么？任何一个点都可以为起点，所以遍历整个二维数组。

2. 如何让它不走重复走已经走过的点？将走过的点置为‘\0‘。

3. 什么时候回溯？当走到边界或者当前元素不等。

`(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != words[k])`

4. 结束条件？word的最后一个元素找到后。

## 4. 实现

```public class Exist12 {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for(int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if(board[i][j] == words[0]) {
return dfs(board, words, i, j, 0);
}
}
}
return false;
}
private boolean dfs(char[][] board, char[] words, int i, int j, int k) {
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != words[k]) return false;
if(k == words.length - 1) return true;
board[i][j] = ‘\0‘;
boolean res = dfs(board, words, i + 1, j, k + 1) || dfs(board, words, i, j + 1, k + 1)
|| dfs(board, words, i, j - 1, k + 1) || dfs(board, words, i - 1, j, k + 1);
board[i][j] = words[k];
return res;
}
}```

## 5. 结语

努力去爱周围的每一个人，付出，不一定有收获，但是不付出就一定没有收获！ 给街头卖艺的人零钱，不和深夜还在摆摊的小贩讨价还价。愿我的博客对你有所帮助(*^▽^*)(*^▽^*)！

如果客官喜欢小生的园子，记得关注小生哟，小生会持续更新(#^.^#)(#^.^#)。

(0)
(0)

© 2014 mamicode.com 版权所有