还是用回溯法,定义一个二维数组存储访问标记,在对任意位置进行深度优先搜索时,先将当前位置为已访问,以避免重复遍历,在所有的可能都搜索完成后,再改回当前位置为未访问
标签: 搜索
https://leetcode.cn/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
提示:
- m == board.length
- n = board[i].length
- 1 <= m, n <= 6
- 1 <= word.length <= 15
- board 和 word 仅由大小写英文字母组成
进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?
二、解题思路还是用回溯法,定义一个二维数组存储访问标记,在对任意位置进行深度优先搜索时,先将当前位置为已访问,以避免重复遍历,在所有的可能都搜索完成后,再改回当前位置为未访问,防止干扰其它位置搜索当前位置。
三、解题方法 3.1 Java实现public class Solution {
boolean find = false;
public boolean exist(char[][] board, String word) {
if (board.length == 0) {
return false;
}
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
backTracking(i, j, board, word, visited, 0);
}
}
return find;
}
void backTracking(int i, int j, char[][] board, String word, boolean[][] visited, int pos) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return;
}
if (visited[i][j] || find || board[i][j] != word.charAt(pos)) {
return;
}
if (pos == word.length() - 1) {
find = true;
return;
}
visited[i][j] = true;
backTracking(i + 1, j, board, word, visited, pos + 1);
backTracking(i - 1, j, board, word, visited, pos + 1);
backTracking(i, j + 1, board, word, visited, pos + 1);
backTracking(i, j - 1, board, word, visited, pos + 1);
visited[i][j] = false;
}
}
四、总结小记
- 2021/6/5 今天假日最后一天