来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
题目描述:
给定一个 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
思路:
因为没有给定起点,所以最开始需要遍历二维数组,寻找起始点。board[start][end] == word的第一个单词的话,就以start,end为起点开始回溯遍历。递归结束还没有找到说明不是这个起点,继续寻找board[start][end]=word.charAt(0)的节点,重复刚才的操作。
实现:
class Solution {
int m = 0;
int n = 0;
boolean flag = false;
public boolean exist(char[][] board, String word) {
m = board.length;
n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (flag) {
return flag;
}
if (word.charAt(0) == board[i][j]) {
dfs(board, word, 0, i, j);
}
}
}
return flag;
}
public void dfs(char[][] board, String word, int index, int start, int end) {
if (index == word.length()) {
flag = true;
return;
}
if (start < 0 || end < 0 || start >= m || end >= n) {
return;
}
if (board[start][end] == '*') {
return;
}
if (word.charAt(index) == board[start][end]) {
char temp = board[start][end];
board[start][end] = '*';
dfs(board, word, index + 1, start + 1, end);
dfs(board, word, index + 1, start - 1, end);
dfs(board, word, index + 1, start, end + 1);
dfs(board, word, index + 1, start, end - 1);
board[start][end] = temp;
}
}
}