ID | Title | Difficulty | |
---|---|---|---|
Loading... |
79. Word Search
Medium
LeetCode
Array, Backtracking, Matrix
Problem
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.
Code
class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == word.charAt(0)){
if(dfs(board, i, j, 0, word, new HashSet<>())){
return true;
}
}
}
}
return false;
}
private boolean dfs(char[][] board, int i, int j, int index, String word, HashSet<String> visited){
if(index == word.length()) return true;
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length
|| visited.contains(i + "," + j)
|| board[i][j] != word.charAt(index)) return false;
visited.add(i + "," + j);
if(dfs(board, i + 1, j, index + 1, word, visited)
|| dfs(board, i - 1, j, index + 1, word, visited)
|| dfs(board, i, j + 1, index + 1, word, visited)
|| dfs(board, i, j - 1, index + 1, word, visited)){
return true;
}
visited.remove(i + "," + j);
return false;
}
}
按 <- 键看上一题!
78. Subsets
按 -> 键看下一题!
80. Remove Duplicates from Sorted Array II