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.
难度:medium
题目:给定2维格子和一单词,在格子中搜索该单词是否存在。
思路:递归四个方向。
Runtime: 8 ms, faster than 84.35% of Java online submissions for Word Search.
Memory Usage: 39 MB, less than 9.32% of Java online submissions for Word Search.
class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (exist(board, i, j, visited, word, 0)) {
return true;
}
}
}
return false;
}
private boolean exist(char[][] board, int i, int j, boolean[][] visited, String word, int idx) {
if (i < 0 || i >= board.length
|| j < 0 || j >= board[i].length
|| visited[i][j]
|| word.charAt(idx) != board[i][j]) {
return false;
}
if (idx == word.length() - 1) {
return true;
}
boolean flg = false;
visited[i][j] = true;
flg = flg || exist(board, i - 1, j, visited, word, idx + 1);
flg = flg || exist(board, i + 1, j, visited, word, idx + 1);
flg = flg || exist(board, i, j - 1, visited, word, idx + 1);
flg = flg || exist(board, i, j + 1, visited, word, idx + 1);
visited[i][j] = false;
return flg;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。