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.
题目要求
在给定一个数组中查找是否存在给定的字符串,查找的方式是当找到一个符合要求的字母后只能在这个字符的上下左右接着查找,并且之前已经用过的字母不能再被使用。
分析
- 采用图的深度优先搜索策略,对于每个相等的字母,分别去找它的上下左右的位置,如果超出搜索范围或者不相等或者已经使用过的就不算找到,当成功搜索到字符串的最后一个字母后返回true,否则返回false。
- 对给定的数组的每个位置都采用上述策略来搜索,只要找到了就返回true,当所有的都搜索完后仍没有找到,返回false。
相关阅读
有关图的深度优先搜索,可以参考下面几篇博客。
https://www.cnblogs.com/llhthinker/p/4844735.html
http://blog.youkuaiyun.com/jrdgogo/article/details/50834627
https://www.cnblogs.com/George1994/p/6399889.html
Java实现
class Solution {
static boolean[][] visited;
public boolean exist(char[][] board, String word) {
visited=new boolean[board.length][board[0].length];
for(int i=0;i<board.length;++i)
for(int j=0;j<board[0].length;++j)
{
if(search(board,word,i,j,0))
return true;
}
return false;
}
public boolean search(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||word.charAt(index)!=board[i][j]||visited[i][j]==true)
return false;
visited[i][j]=true;
if(search(board,word,i-1,j,index+1)
||search(board,word,i+1,j,index+1)
||search(board,word,i,j-1,index+1)
||search(board,word,i,j+1,index+1))
return true;
visited[i][j]=false;
return false;
}
}