【LeetCode】 79. Word Search 单词搜索(Medium)(JAVA)
题目地址: https://leetcode.com/problems/word-search/
题目描述:
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.
Constraints:
1. board and word consists only of lowercase and uppercase English letters.
2. 1 <= board.length <= 200
3. 1 <= board[i].length <= 200
4. 1 <= word.length <= 10^3
题目大意
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
解题方法
1、采用递归算法
2、采用DFS(深度优先搜索)
3、因为不能重复使用,搜索过的元素先置为空,后面再恢复
class Solution {
public boolean exist(char[][] board, String word) {
if (board.length == 0 || board[0].length == 0) return word.length() == 0;
if (word.length() == 0) return true;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != word.charAt(0)) continue;
if (eH(board, word, i, j, 0)) return true;
}
}
return false;
}
public boolean eH(char[][] board, String word, int i, int j, int index) {
if (index >= word.length()) return true;
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length) return false;
if (board[i][j] != word.charAt(index)) return false;
char temp = board[i][j];
board[i][j] = ' ';
boolean flag = eH(board, word, i - 1, j, index + 1) || eH(board, word, i + 1, j, index + 1) || eH(board, word, i, j - 1, index + 1) || eH(board, word, i, j + 1, index + 1);
board[i][j] = temp;
return flag;
}
}
执行用时 : 7 ms, 在所有 Java 提交中击败了 70.42% 的用户
内存消耗 : 43.4 MB, 在所有 Java 提交中击败了 17.21% 的用户