回溯算法

class Solution {
    public boolean exist(char[][] board, String word) {
 // 二维网格的长和宽
        int h = board.length, w = board[0].length;
        // 设置一个二维数组用于标记节点是否被访问过
        boolean[][] visited = new boolean[h][w];
        // 对二维网格中的每个结点都进行搜索
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                boolean flag = check(board, visited, i, j, word, 0);
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }

    // 在二维网格中判断board[i][j] 是否等于 s[k]
    public boolean check(char[][] board, boolean[][] visited, int x, int y, String word, int index) {
        // 如果搜索的点与字符串中的第k个字符不相同
        if (board[x][y] != word.charAt(index)) {
            return false;
        }
        // 整个字符串都已经找到了,返回true 
        else if (index == word.length() - 1) {
            return true;
        }
        // 访问结点,并继续搜索
        visited[x][y] = true;
        // 继续搜索的四个方向(上下左右)
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        // 用于标识接下来的搜索是否成功
        boolean result = false;
        for (int[] dir : directions) {
            int newx = x + dir[0], newy = y + dir[1];
            // 判断新坐标是否越界
            if (newx >= 0 && newx < board.length && newy >= 0 && newy < board[0].length) {
                if (!visited[newx][newy]) {
                    boolean flag = check(board, visited, newx, newy, word, index + 1);
                    if (flag) {
                        result = true;
                        break;
                    }
                }
            }
        }
        // 回溯的返回过程
        visited[x][y] = false;
        return result;
    }
}
全部评论

相关推荐

03-28 19:11
铜陵学院 C++
有礼貌的山羊追赶太阳:太典了,连笔试都没有开始就因为HC满了而结束了,而且还卡你不让你再投其他部门的。
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务