字母迷宫
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 208 ms, 内存: 18.4 MB
/*
* 思路:
* 1. 使用Stream API来简化遍历操作。
* 2. 由于Stream API不适合处理复杂的递归操作,因此这里只能在基础遍历中使用。
* 3. 核心逻辑仍然使用DFS进行深度优先搜索。
*/
import java.util.stream.IntStream;
public class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
return IntStream.range(0, m)
.boxed()
.flatMap(i -> IntStream.range(0, n)
.mapToObj(j -> new int[]{i, j}))
.anyMatch(pos -> dfs(board, word, 0, pos[0], pos[1], visited));
}
private boolean dfs(char[][] board, String word, int index, int x, int y, boolean[][] visited) {
if (index == word.length()) {
return true;
}
if (x < 0 || y < 0 || x >= board.length || y >= board[0].length || visited[x][y] || board[x][y] != word.charAt(index)) {
return false;
}
visited[x][y] = true;
boolean found = dfs(board, word, index + 1, x + 1, y, visited) ||
dfs(board, word, index + 1, x - 1, y, visited) ||
dfs(board, word, index + 1, x, y + 1, visited) ||
dfs(board, word, index + 1, x, y - 1, visited);
visited[x][y] = false;
return found;
}
}
解释
方法:
此题解采用深度优先搜索(DFS)策略来遍历字母迷宫,并试图在其中寻找目标单词。从迷宫的每一个格子开始,尝试向四个方向(上、下、左、右)扩展搜索,以匹配目标单词的每个字符。搜索过程中使用递归函数dfs(i, j, k)来实现,其中i和j表示当前的行和列位置,k表示目标单词中当前正在匹配的字符索引。如果当前位置越界或字符不匹配,则返回False。如果所有字符都成功匹配(即k等于单词长度减一),则返回True。为了防止在DFS过程中重复使用同一单元格,将当前单元格的值暂时设置为空字符串,并在搜索返回后恢复原值。只要从任意起点开始的DFS返回True,就表示可以在迷宫中找到目标单词。
时间复杂度:
O(m*n*4^L)
空间复杂度:
O(L)
代码细节讲解
🦆
在DFS中,如何有效地处理格子的临时标记和恢复过程,以确保不影响其他搜索路径?
▷🦆
DFS递归调用栈在最坏情况下的深度是如何计算的,考虑到单词长度和棋盘的大小?
▷🦆
为什么选择深度优先搜索而不是广度优先搜索来解决这个问题?广度优先搜索在这个场景中的表现如何?
▷🦆
在代码实现中,如果单词的第一个字符在棋盘中出现多次,算法是否会尝试所有可能的起始位置?
▷