79. 单词搜索。
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成
算法分析
解题思路
DFS
从单词矩阵中枚举每个单词的起点,从该起点出发往四周dfs搜索目标单词,并记录当前枚举到第几个单词,若当前搜索到的位置(i,j)的元素恰好是word单词第depth个字符,则继续dfs搜索,直到depth到最后一个字符则表示有了符合的方案,返回true
注意:搜索过的位置继续搜索下一层时,需要对当前位置进行标识,表示已经搜索
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (dfs(board, words, 0, i, j)) return true;
}
}
return false;
}
int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1}; // 左上右下
private boolean dfs(char[][] board, char[] words, int u, int x, int y) {
if (board[x][y] != words[u]) return false;
if (u == words.length - 1) return true;
char t = board[x][y];
board[x][y] = '.';
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= board.length || b < 0 || b >= board[0].length || board[a][b] == '.') continue;
if (dfs(board, words, u + 1, a, b)) return true;
}
board[x][y] = t;
return false;
}
}
复杂性分析
时间复杂度:O(mn * 3^l)
空间复杂度:O(m+n)