79. 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.
For example,
Given board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
题意:
给定一个2D面板和一个单词,查找这个单词是否存在于面板中。
单词可以由相邻单元格的字母构成,相邻的单元格是水平或垂直相邻的单元格。同一个字母单元不能超过一次使用。
思路:
方法一:
也是典型的递归回溯,深度优先遍历的题目,但是因为同一个字母单元不能超过一次使用,所以要有标记矩阵标记此元素是否可以访问,从上下左右四个方向进行DFS。需要注意的就是访问一个字母后visited标识1,当DFS调用返回后,如果还没有找完,应该让visited置0,并返回false。
注意理解的带返回值的终止递归回溯算法。
1 | /**************************************************************************************************************** |
方法二:
递归回溯法,此法一是省去标记数组,减少空间复杂度,二是递归回溯函数内部递归结束条件控制的很好,所以能提高效率,值得学习的好方法。
1 | class Solution { |
Java Code
1 | class Solution { |