您的位置:首页 > 其它

Leetcode 题解 - 搜索--Backtracking(11):在矩阵中寻找字符串

2019-05-27 10:07 387 查看

[LeetCode] 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 =

[code][
["ABCE"],
["SFCS"],
["ADEE"]
]

word = 

"ABCCED"
, -> returns 
true
,
word = 
"SEE"
, -> returns 
true
,
word = 
"ABCB"
, -> returns 
false
.

 

这道题是典型的深度优先遍历DFS的应用,原二维数组就像是一个迷宫,可以上下左右四个方向行走,我们以二维数组中每一个数都作为起点和给定字符串做匹配,我们还需要一个和原数组等大小的visited数组,是bool型的,用来记录当前位置是否已经被访问过,因为题目要求一个cell只能被访问一次。如果二维数组board的当前字符和目标字符串word对应的字符相等,则对其上下左右四个邻字符分别调用DFS的递归函数,只要有一个返回true,那么就表示可以找到对应的字符串,否则就不能找到,具体看代码实现如下:

 

[code]class Solution {
private final static int[][] direction={{1,0}, {-1,0}, {0,1}, {0,-1}};
private int m;
private int n;
public boolean exist(char[][] board, String word) {
if(word.length() == 0 || word == null)
return true;
if(board == null || board.length == 0 || board[0].length == 0)
return false;
m = board.length;
n = board[0].length;
//要明确的一点就是每个点都是从头搜索一遍 你的visited矩阵对每个点都是新的
boolean[][] visited = new boolean[m]
;
for(int i=0; i<m;i++){
for(int j = 0; j<n; j++){
if(help(0, i, j, visited, board, word))
return true;
}
}
return false;

}

private boolean help(int curlen, int r, int c, boolean[][] visited,
final char[][] board, final String word){
//如果长度等于word。length说明是0-n n-1是满足条件的字符 所以可以返回true
if (curlen == word.length()) {
return true;
}

if(r < 0 || r >= m || c < 0 || c >= n || visited[r][c] ||
board[r][c] != word.charAt(curlen))
return false;
//这种情况是和 visited[r][c]对应的 说明我走过这个点了 先标注有以下
visited[r][c] = true;

for(int[] d: direction){
//这里是重点 如果在四个方向的递归之中找到了满足条件的情况 就返回true
if(help(curlen+1, r+d[0], c+d[1], visited, board, word))
return true;
}
//上面都没有返回说明这个点不可能是满足条件的点 所以标回为false不影响下次判断
visited[r][c] = false;

return false;

}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: