DFS + Back tracking:
1. 总是要抱着recursion的大腿的
2. 标记visited
3. 要还原还原!一般结构是 revision -》 recursion -》 restore
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word = "ABCB", -> returns false.
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || word.length() == 0) return false;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
boolean res = find(board, word, i, j, 0);
if (res) {
return true;
}
}
}
}
return false;
}
public boolean find(char[][]board, String word, int i, int j, int start) {
if (start == word.length()) {
return true;
}
if ( i < 0 || i >= board.length
||j < 0 || j >= board[0].length
|| word.charAt(start) != board[i][j] ) {
return false;
}
board[i][j] = '*';
boolean res = (find(board, word, i+1, j, start+1) ||
find(board, word, i-1, j, start+1) ||
find(board, word, i, j+1, start+1) ||
find(board, word, i, j-1, start+1));
board[i][j] = word.charAt(start);
return res;
}
}
本文探讨了使用DFS(深度优先搜索)+回溯算法解决迷宫问题的方法,详细介绍了算法的核心思想和实现步骤,通过实例展示了如何利用这些技术在给定的二维矩阵中寻找指定单词路径。

1219

被折叠的 条评论
为什么被折叠?



