给定一个二维网格和一个单词,找出该单词是否存在于网格中。
    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    示例:
    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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/word-search


    回溯问题,其实这题应该还是DFS的问题,定一个方向标找他四连通位置上的值有没有和给定的字符串一样的
    如果有,就再往下,如果发现此路不通就回溯

    1. class Solution {
    2. //定义一个方向标
    3. static final int[][] DIRS = new int[][]{{-1,0}, {1,0}, {0,-1},{0,1}};
    4. static int row , col;
    5. public static boolean exist(char[][] board, String word){
    6. //特殊情况判断
    7. if (board == null || board.length == 0 || board[0].length == 0){
    8. return false;
    9. }
    10. if (word.length() == 0){
    11. return true;
    12. }
    13. row = board.length;
    14. col = board[0].length;
    15. boolean [][] isVisited = new boolean[row][col];
    16. for (int i = 0; i < row; i++) {
    17. for (int j = 0; j < col; j++) {
    18. if (dfs(0,i,j,board,isVisited,word)){
    19. return true;
    20. }
    21. }
    22. }
    23. return false;
    24. }
    25. public static boolean dfs(int curLen, int i ,int j, char [][] board, boolean [][] isVisited,String word){
    26. if (curLen == word.length()) {
    27. return true;
    28. }
    29. //排除所有的不符合的条件
    30. if (i < 0 || i >= row || j < 0 || j >= col || board[i][j] != word.charAt(curLen) || isVisited[i][j]) {
    31. return false;
    32. }
    33. //进来了就说明这个点已经访问过了
    34. isVisited[i][j] = true;
    35. for (int[] d : DIRS) {
    36. if (dfs(curLen + 1, i + d[0], j + d[1], board, isVisited, word)) {
    37. return true;
    38. }
    39. }
    40. isVisited[i][j] = false;
    41. return false;
    42. }
    43. }