设计一个递归算法,在二维矩阵中搜索指定的字符串。
递归算法:在二维矩阵中搜索指定的字符串
递归算法可以用于在二维矩阵中搜索指定的字符串。下面是一个示例算法,用于在二维矩阵中搜索目标字符串。
public class Solution {
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (search(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}
public boolean search(char[][] board, int i, int j, String word, int index) {
if (index == word.length()) {
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index)) {
return false;
}
char temp = board[i][j];
board[i][j] = ' ';
boolean found = search(board, i + 1, j, word, index + 1) ||
search(board, i - 1, j, word, index + 1) ||
search(board, i, j + 1, word, index + 1) ||
search(board, i, j - 1, word, index + 1);
board[i][j] = temp;
return found;
}
}
在上面的示例中,递归算法使用深度优先搜索(DFS)来在二维矩阵中搜索指定的字符串。该算法首先以每个矩阵元素为起点,通过回溯的方式递归搜索相邻的元素,直到找到目标字符串或者穷尽所有可能的路径。