一、题目粗心
标签: 搜寻
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 明天假日最初一天