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; } }
相关文章推荐
- Leetcode 题解 - 搜索--Backtracking(21):分割字符串使得每个部分都是回文数
- Leetcode 题解 - 搜索--Backtracking(15):组合
- Leetcode 题解 - 搜索--Backtracking(20):含有相同元素求子集
- Leetcode 题解 - 搜索--Backtracking(12):输出二叉树中所有从根到叶子的路径
- Leetcode 题解 - 搜索--Backtracking(17):1-9 数字的组合求和
- Leetcode 题解 - 搜索--Backtracking(13):Permutations 全排列
- Leetcode 题解 - 搜索--Backtracking(14):全排列2
- Leetcode 题解 - 搜索--Backtracking(19):子集合
- 【题解】【矩阵】【DP】【Leetcode】Minimum Path Sum
- 【leetcode数组和字符串】寻找数组的中心索引
- 用python写leetcode【9】 --搜索二维矩阵 II(240)
- [LeetCode] Search a 2D Matrix 搜索一个二维矩阵
- 【题解】【字符串】【BFS】【Leetcode】Word Ladder
- leetcode-14. Longest Common Prefix(寻找字符串数组最长公共前缀)
- LeetCode 74. Search a 2D Matrix(搜索矩阵)
- leetcode题3 寻找字符串不包含重复字符的最长子字符串
- LeetCode 415. Add Strings题解 字符串加和
- LeetCode题解-11-Container With Most Water
- leetcode 刷题记录(高频算法面试题汇总) -- 搜索二维矩阵 ii
- Word Search, 在矩阵中寻找字符串,回溯算法