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.
- Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
解法
将矩阵中的每一个字符当作起点与word做匹配,然后对其上下左右分别调用dfs,如果有满足条件的则返回true,将矩阵遍历完之后还是没有满足条件的则返回false
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0)
return false;
int n = board.length, m = board[0].length;
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (dfs(board, word, visited, 0, i, j))
return true;
}
return false;
}
private boolean dfs(char[][] board, String word, boolean[][] visited, int level, int i, int j) {
// TODO Auto-generated method stub
if (level == word.length())
return true;
int n = board.length, m = board[0].length;
if (i < 0 || j < 0 || i >= n || j >= m || visited[i][j] || board[i][j] != word.charAt(level))
return false;
visited[i][j] = true;
boolean res = dfs(board, word, visited, level + 1, i, j + 1) || dfs(board, word, visited, level + 1, i + 1, j)
|| dfs(board, word, visited, level + 1, i - 1, j) || dfs(board, word, visited, level + 1, i, j - 1);
visited[i][j]=false;
return res;
}
Runtime: 7 ms, faster than 86.57% of Java online submissions for Word Search.
Memory Usage: 40.3 MB, less than 40.06% of Java online submissions for Word Search.
这篇博客探讨了LeetCode中的Word Search问题,通过给定的2D网格寻找是否存在指定单词。文章提供了示例,并解释了解决方案,即从每个矩阵字符开始,使用深度优先搜索(DFS)检查水平或垂直相邻的字母。如果找到匹配的路径,则返回true,否则返回false。该解法的运行时间为7毫秒,优于86.57%的Java在线提交,内存使用为40.3 MB,低于40.06%的Java在线提交。

2464

被折叠的 条评论
为什么被折叠?



