搜索---广度优先

广度优先搜索一层一层地进行遍历,每层遍历都以上一层遍历的结果作为起点,遍历一个距离能访问到的所有节点。需要注意的是,遍历过的节点不能再次被遍历。
每一层遍历的节点都与根节点距离相同。设 di 表示第 i 个节点与根节点的距离,推导出一个结论:对于先遍历的节点 i 与后遍历的节点 j,有 di <= dj。利用这个结论,可以求解最短路径等 最优解 问题:第一次遍历到目的节点,其所经过的路径为最短路径。应该注意的是,使用 BFS 只能求解无权图的最短路径,无权图是指从一个节点到另一个节点的代价都记为 1。

在程序实现 BFS 时需要考虑以下问题:

队列:用来存储每一轮遍历得到的节点;
标记:对于遍历过的节点,应该将它标记,防止重复遍历。

1.计算在网格中从原点到特定点的最短路径长度

/*
    * 计算在网格中从原点到特定点的最短路径长度
    * 在一个 N × N 的方形网格中,每个单元格有两种状态:空(0)或者阻塞(1)。
    * */
    public int shortestPathBinaryMatrix(int[][] grid) {
        int direction[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
        int n = grid.length;
        Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
        if (grid[0][0] == 0) {
            if (n == 1) return 1;
            queue.add(new Pair<>(0, 0));
        }
        int path = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            path++;
            while (size-- != 0) {//把每层的节点遍历完
                Pair<Integer, Integer> curElem = queue.poll();
                int x = curElem.getKey();
                int y = curElem.getValue();
                for (int i = 0; i < 8; i++) {
                    int curx = direction[i][0] + x, cury = direction[i][1] + y;
                    if (curx < 0 || curx >= n || cury < 0 || cury >= n || grid[curx][cury] == 1) continue;
                    if (curx == n - 1 && cury == n - 1) return path + 1;
                    queue.add(new Pair<>(curx, cury));
                    grid[curx][cury] = 1;//标记一下已走过
                }
            }
        }
        return -1;
    }

2. 组成整数的最小平方数数量

    /*
    * 题目:完全平方数
    * 描述:给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。
    * 你需要让组成和的完全平方数的个数最少。
    * 分析:
    * 可以将每个整数看成图中的一个节点,如果两个整数之差为一个平方数,那么这两个整数所在的节点就有一条边。
    * 要求解最小的平方数数量,就是求解从节点 n 到节点 0 的最短路径。
    * 本题也可以用动态规划求解
    * */
    public int numSquares(int n) {
        if (n == 0) return 0;
        List<Integer> squares = squareWithinN(n);
        Queue<Integer> queue = new LinkedList<>();
        queue.add(n);
        int book[] = new int[n];
        int path = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            path++;
            while (size-- != 0) {
                int cur = queue.poll();
                for (Integer square : squares) {
                    int newNode = cur - square;
                    if (newNode < 0) break;
                    if (newNode == 0) return path;
                    if (book[newNode] == 1) continue;
                    queue.add(newNode);
                    book[newNode] = 1;
                }
            }
        }
        return -1;
    }

    //求n以内的平方数
    public List<Integer> squareWithinN(int n) {
        List<Integer> squares = new LinkedList<>();
        for (int a = 1; a <= Math.sqrt(n); a++) {
            squares.add(a * a);
        }
        return squares;
    }

3. 最短单词路径

    /*
    * 题目:给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。
    * 转换需遵循如下规则:
    * 每次转换只能改变一个字母
    * 转换过程中的中间单词必须是字典中的单词。
    * 说明:
    * 如果不存在这样的转换序列,返回 0。所有单词具有相同的长度。所有单词只由小写字母组成。字典中不存在重复的单词。你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
    *
    * */
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        int n = wordList.size();
        /*判断endWord是否在字典中,并找到所在位置*/
        int endWordIndex = -1;
        for (int i = 0; i < n; i++) {
            String word = wordList.get(i);
            if (word.equals(endWord)) {
                endWordIndex = i;
                break;
            }
        }
        if (endWordIndex == -1) return 0;
        /*建立一个连通图,graph[i]中存储着第i个词可转化为字典中其它哪些词*/
        wordList.add(beginWord);
        n = wordList.size();
        List<Integer> gragh[] = new List[n];
        for (int i = 0; i < n; i++) {
            List<Integer> curlist = new LinkedList<>();
            String curWord = wordList.get(i);
            for (int j = 0; j < i; j++) {
                String otherWord = wordList.get(j);
                if (isConnect(curWord, otherWord)) {
                    curlist.add(j);
                    gragh[j].add(i);
                }
            }
            gragh[i] = curlist;
        }
        /*广度优先搜索*/
        return findLadderLength(gragh, wordList, endWordIndex);
    }

    public int findLadderLength(List<Integer>[] gragh, List<String> wordList, int endWordIndex) {
        Queue<Integer> queue = new LinkedList<>();
        int n = gragh.length;
        boolean book[] = new boolean[n];
        queue.add(n - 1);
        int path = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            path++;
            while (size-- != 0) {
                int index = queue.poll();
                List<Integer> linkit = gragh[index];
                for (int curlinkIndex : linkit) {
                    if (curlinkIndex == endWordIndex) return path;
                    if (book[curlinkIndex]) continue;
                    queue.add(curlinkIndex);
                    book[curlinkIndex] = true;
                }
            }
        }
        return 0;
    }

    /*判断s1和s2是否可以互相转化*/
    public boolean isConnect(String s1, String s2) {
        int differ = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                differ++;
            }
        }
        return differ == 1;
    }

参考:github—CyC2018题解

发布了184 篇原创文章 · 获赞 60 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/StubbornAccepted/article/details/103078977