给定一个二维网格和一个单词,找出该单词是否存在于网格中
https://leetcode-cn.com/problems/word-search/
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用
示例1:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]给定 word = “ABCCED”, 返回 true
给定 word = “SEE”, 返回 true
给定 word = “ABCB”, 返回 false
提示:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Java解法
思路:
- ~~必须按顺序相邻才视为有效,因为相邻可能有多个,所以可以考虑用回溯处理,直到完成要求即可、但是没有考虑好已用char的处理、~~采用二维数组进行记录,但错误的复制导致冗余,回溯机制是可以通过复位来避免多次记录的
- 参考官方解修改
package sj.shimmer.algorithm.m2;
/**
* Created by SJ on 2021/3/8.
*/
class D43 {
public static void main(String[] args) {
// System.out.println(exist(
// new char[][]{
// new char[]{'A', 'B', 'C', 'E'},
// new char[]{'S', 'F', 'C', 'S'},
// new char[]{'A', 'D', 'E', 'E'}
// }, "CESCC"));
System.out.println(exist(
new char[][]{
new char[]{'A','B', 'C', 'E'},
new char[]{'S','F', 'E', 'S'},
new char[]{'A','D', 'E', 'E'}
},
"ABCESEEEFS"));
// System.out.println(exist(
// new char[][]{
// new char[]{'A', 'B'},
// }, "BA"));
}
public static boolean exist(char[][] board, String word) {
if (board==null) {
return false;
}
int rowLength = board.length;
int columnLength = board[0].length;
boolean[][] path = new boolean[rowLength][columnLength];
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < columnLength; j++) {
boolean result = backTrace(board, path, i, j, word, 0);
if (result) {
return true;
}
}
}
return false;
}
public static boolean backTrace(char[][] board, boolean[][] path, int row, int column, String word, int index) {
if (row < 0 || column < 0 || row >= board.length || column >= board[row].length) {
return false;
}
if (path[row][column]) {//经历过
return false;
}
if (word.charAt(index)!=board[row][column]) {
return false;
}else if (index == word.length()-1) {
return true;
}
path[row][column] = true;//经历
boolean result = backTrace(board, path, row - 1, column, word, index + 1) ||
backTrace(board, path, row + 1, column, word, index + 1) ||
backTrace(board, path, row, column - 1, word, index + 1) ||
backTrace(board, path, row, column + 1, word, index + 1);
path[row][column] = false;//恢复
return result;
}
}
官方解
https://leetcode-cn.com/problems/word-search/solution/dan-ci-sou-suo-by-leetcode-solution/
-
深度优先搜索
上方解法
- 时间复杂度:O(MN⋅3 ^L ) M,N 为网格的长度与宽度
- 空间复杂度:O(MN)