LeetCode 79 单词搜索
LeetCode79 单词搜索
题目描述
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
样例
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
算法分析
- 暴力搜索
- 每个单元格的字母只能允许使用一次
- 起点,每个方向,递归下去
时间复杂度
Java代码
class Solution {
static int n,m;
static int[] dx = new int[]{0,-1,0,1};
static int[] dy = new int[]{-1,0,1,0};
static boolean dfs(char[][] board, String word, int deepth, int x, int y){
if(board[x][y] != word.charAt(deepth)) return false;
if(deepth == word.length() - 1) return true;
char c = board[x][y];
board[x][y] = '*';
for(int i = 0; i < 4; i ++){
int u = x + dx[i];
int v = y + dy[i];
if(u < 0 || u >=n || v < 0 || v >= m) continue;
if(board[u][v] == '*') continue;
if(dfs(board,word,deepth+1,u,v)) return true;
}
board[x][y] = c;
return false;
}
public boolean exist(char[][] board, String word) {
n = board.length;
m = board[0].length;
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j ++){
if(board[i][j]==word.charAt(0)){
if(dfs(board,word,0,i,j)){
return true;
}
}
}
}
return false;
}
}

浙公网安备 33010602011771号