leetcode链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

题目

image.png

解法

使用 dfs(深度遍历搜索)

  1. class Solution {
  2. public boolean exist(char[][] board, String word) {
  3. // 行数
  4. int row = board.length;
  5. // 列数
  6. int col = board[0].length;
  7. char[] chars = word.toCharArray();
  8. for (int i = 0; i < row; i++) {
  9. for (int j = 0; j < col; j++) {
  10. if (dfs(board, chars, i, j, 0)) {
  11. return true;
  12. }
  13. }
  14. }
  15. return false;
  16. }
  17. boolean dfs(char[][] board, char[] word, int i, int j, int index) {
  18. // 参数说明,index指查到字符串的第几个字符
  19. // 边界判断
  20. // 1.如果越界直接返回false
  21. // 2.如果当前字符不等于board[i][j],说明此路不通,返回false
  22. if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[index]) {
  23. return false;
  24. }
  25. // 如果index=word.length,说明匹配成功,返回true
  26. if (index == word.length-1 ) {
  27. return true;
  28. }
  29. // 保存中间值,方便复原
  30. char tmp = board[i][j];
  31. // 将当前位置标记为已访问
  32. board[i][j] = '.';
  33. boolean res = dfs(board, word, i - 1, j, index + 1) ||
  34. dfs(board, word, i + 1, j, index + 1) ||
  35. dfs(board, word, i, j - 1, index + 1) ||
  36. dfs(board, word, i, j + 1, index + 1);
  37. // 复原环境
  38. board[i][j] = tmp;
  39. return res;
  40. }
  41. }