题目
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.
示例1:
1 | board = |
提示:
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
解法
解法一:
深度优先遍历
分解为以下步骤:
- 遍历board中的每个字符,找到搜索起始点-即和word字符串第一个相等的char
- 对每个起始点,进行dfs搜索
- 如果搜索的时候,发现index已经等于word的长度了,则表示已经找到匹配的字符串了,直接返回
- 如果列或者行越界了,小于0或者大于列长度或者大于行长度,又或者当前的字符串和word对应位置的字符串不一致,说明当前路径是不可行的,直接返回
- 把当前节点置为一个特殊字符,表示已经使用,不可再用第二次,继续从当前节点的上下左右位置开始搜索
- 把当前节点置为原字符,供下次搜索使用
JAVA
1 | public boolean exist(char[][] board, String word) { |