题目
注意:此题跟岛屿的数量对比来看,增加了回溯的过程,岛屿题并无回溯。
法1:DFS
必须掌握方法!
class Solution {public boolean exist(char[][] board, String word) {char[] charArr = word.toCharArray();int m = board.length, n = board[0].length;for (int i = 0; i < m; ++i) {for (int j = 0; j < n; ++j) {int[][] used = new int[m][n];if (dfs(board, charArr, used, i, j, 0)) {return true;}}}return false;}public boolean dfs(char[][] board, char[] charArr, int[][] used, int i, int j, int curIndex) {if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || used[i][j] == 1|| curIndex >= charArr.length || board[i][j] != charArr[curIndex]) {return false;}if (curIndex == charArr.length - 1 && board[i][j] == charArr[curIndex]) {return true;}used[i][j] = 1;boolean res = dfs(board, charArr, used, i - 1, j, curIndex + 1) || dfs(board, charArr, used, i + 1, j, curIndex + 1) || dfs(board, charArr, used, i, j - 1, curIndex + 1) || dfs(board, charArr, used, i, j + 1, curIndex + 1);if (res) {return true;} else {used[i][j] = 0;return false;}}
}