题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如
a b t g
c f c s
j d e h
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
练习地址
lc
实现
典型回溯
思路:
1 起点:任选一个格子,假设字符为ch
2 若路径中第i个字符不是ch,这个格子不可能处在路径上的第i个位置
3 若路径中第i个字符是ch,到相邻格子寻找第i+1个字符
4 重复上述过程
实现:
方法1:算法小抄_回溯+jz
执行用时:7 ms, 在所有 Java 提交中击败了40.65%的用户
内存消耗:40.3 MB, 在所有 Java 提交中击败了56.99%的用户
public boolean exist(char[][] board, String word) {
if (board == null || board.length < 1 || board[0].length < 1 || word == null)
return false;
int rows = board.length;
int cols = board[0].length;
boolean[][] visited = new boolean[rows][cols];// 默认是false
int pathLen = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (existCore(board, rows, cols, row, col, word, pathLen, visited))
return true;
}
}
return false;
}
boolean existCore(char[][] board, int rows, int cols, int row, int col, String word, int pathLen, boolean[][] visited) {
// 满足结束条件,记录路径,返回
if (row < 0 || row >= rows || col < 0 || col >= cols
|| board[row][col] != word.charAt(pathLen)
|| visited[row][col])
return false;
if (pathLen == word.length() - 1)
return true;
boolean isExist = false;
// 做选择(in 选择列表)
++pathLen;
visited[row][col] = true;
// 递归(路径,选择列表)
isExist = existCore(board, rows, cols, row, col - 1, word, pathLen, visited)
|| existCore(board, rows, cols, row - 1, col, word, pathLen, visited)
|| existCore(board, rows, cols, row, col + 1, word, pathLen, visited)
|| existCore(board, rows, cols, row + 1, col, word, pathLen, visited);
//撤回
if (!isExist) {
--pathLen;
visited[row][col] = false;
}
return isExist;
}
方法2:lc解法
执行用时:
5 ms, 在所有 Java 提交中击败了98.10%的用户
内存消耗:40.5 MB, 在所有 Java 提交中击败了15.53%的用户
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(dfs(board, words, i, j, 0)) return true;
}
}
return false;
}
boolean dfs(char[][] board, char[] word, int i, int j, int k) {
if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
if(k == word.length - 1) return true;
board[i][j] = '\0';
boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
board[i][j] = word[k];
return res;
}
}
作者:jyd
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。