Algorithm Notes
  • Introduction
  • Search & Backtracking 搜索与回溯
    • Tree 与 BackTracking 的比较
    • Subsets, Combination 与 Permutation
    • Subsets & Combinations & Combination Sum
    • 枚举法
    • N 皇后 + 矩阵 Index Trick
    • Sudoku 数独 + 矩阵 Index Trick
    • Word Ladder I & II
    • Number of ways 类
    • DFS flood filling
    • Strobogrammatic 数生成
    • String 构造式 DFS + Backtracking
    • Word Pattern I & II
    • (G) Binary Watch
    • (FB) Phone Letter Combination
    • 常见搜索问题的迭代解法
  • String,字符串类
    • 多步翻转法
    • Substring 结构和遍历
    • Palindrome 问题
    • Palindrome Continued
    • String / LinkedList 大数运算
    • 序列化与压缩
    • 5/24 String 杂题
    • Knuth–Morris–Pratt 字符串匹配
    • Lempel–Ziv–Welch 字符串压缩算法
    • (G) Decode String
    • (G) UTF-8 Validation
  • Binary Tree,二叉树
    • 各种 Binary Tree 定义
    • LCA 类问题
    • 三序遍历,vertical order
    • Post order traversal 的应用
    • Min/Max/Balanced Depth
    • BST
    • 子树结构
    • Level Order traversal
    • Morris 遍历
    • 修改结构
    • 创建 / 序列化
    • 子树组合,BST query
    • 路径与路径和
    • NestedInteger 类
    • (FB) 从 Binary Tree Path 看如何递归转迭代
    • (FB) Binary Tree Path 比较路径大小
    • 比较好玩的 Binary Tree 概率题
  • Segment & Fenwick Tree,区间树
    • Segment Tree 基础操作
    • Segment Tree 的应用
    • Fenwick Tree (Binary Indexed Tree)
    • Range Sum Query 2D - Immutable
  • Union-Find,并查集
    • Union-Find,并查集基础
    • Union-Find, 并查集应用
  • Dynamic Programming, 动态规划
    • 6/20, 入门 House Robber
    • 7/12, Paint Fence / House
    • 6/24, 滚动数组
    • 6/24, 记忆化搜索
    • 6/24, 博弈类 DP
    • 博弈类DP, Flip Game
    • 6/25, 区间类DP
    • 6/27, subarray 划分类,股票
    • 7/2, 字符串类
    • Bomb Enemies
    • 8/2,背包问题
    • (G) Max Vacation
    • (11/4新增) AST 子树结构 DP
  • LinkedList,链表
    • 6/9, LinkedList,反转与删除
    • 6/11, LinkedList 杂题
    • (FB) 链表的递归与倒序打印
  • LinkedIn 面经,算法题
    • 6/17, LinkedIn 面经题
    • 6/28, LinkedIn 面经题
    • 7/6, LinkedIn 面经
    • Shortest Word Distance 类
    • DFA Parse Integer
  • Two Pointers,双指针
    • 3 Sum, 3 Sum Closest / Smaller, 4 Sum
    • 对撞型,灌水类
    • 对撞型,partition类
    • Wiggle Sort I & II
    • 双指针,窗口类
    • 双指针,窗口类
    • Heap,排序 matrix 中的 two pointers
  • Bit & Math,位运算与数学
    • Bit Manipulation,对于 '1' 位的操作
    • Math & Bit Manipulation, Power of X
    • 坐标系 & 数值计算类
    • Add Digits
    • 用 int 做字符串 signature
  • Interval 与 扫描线
    • Range Addition & LCS
    • 7/5, Interval 类,扫描线
  • Trie,字典树
    • 6/9, Trie, 字典树
  • 单调栈,LIS
    • 4/13 LIS
    • 栈, 单调栈
    • Largest Divisible Subset
  • Binary Search 类
    • Matrix Binary Search
    • Array Binary Search
    • Find Peak Element I & II
    • **Median of Two Sorted Arrays
  • Graph & Topological Sort,图 & 拓扑排序
    • 有向 / 无向 图的基本性质和操作
    • 拓扑排序, DFS 做法
    • 拓扑排序, BFS 做法
    • Course Schedule I & II
    • Alien Dictionary
    • Undirected Graph, BFS
    • Undirected Graph, DFS
    • 矩阵,BFS 最短距离探索
    • 欧拉回路,Hierholzer算法
    • AI, 迷宫生成
    • AI, 迷宫寻路算法
    • (G) Deep Copy 无向图成有向图
  • 括号与数学表达式的计算
  • Iterator 类
  • Majority Element,Moore's Voting
  • Matrix Inplace Operations
  • 常见数据结构设计
  • (G) Design / OOD 类算法题
  • 随机算法 & 数据结构
  • (FB) I/O Buffer
  • (FB) Simplify Path, H-Index I & II
  • (FB) Excel Sheet, Remove Duplicates
  • Integer 的构造,操作,序列化
  • Frequency 类问题
  • Missing Number 类,元素交换,数组环形跳转
  • 8/10, Google Tag
  • (FB) Rearrange String k Distance Apart
  • Abstract Algebra
    • Chap1 -- Why Abstract Algebra ?
    • Chap2 -- Operations
    • Chap3 -- The Definition of Groups
Powered by GitBook
On this page
  • directed graph BFS 里靠 indegree = 0 判断加入队列;
  • undirected graph BFS 里靠 degree = 0 判断加入队列;
  • Minimum Height Trees
  • Graph Valid Tree
  • Clone Graph
  • Copy List with Random Pointer

Was this helpful?

  1. Graph & Topological Sort,图 & 拓扑排序

Undirected Graph, BFS

PreviousAlien DictionaryNextUndirected Graph, DFS

Last updated 4 years ago

Was this helpful?

directed graph BFS 里靠 indegree = 0 判断加入队列;

undirected graph BFS 里靠 degree = 0 判断加入队列;

论坛里看到的,非常赞的思路。

先说下自己一个 TLE 的初始尝试:根据所有 Edges 建 ArrayList[] 的 Graph,同时存每个点的 Adjacency lists,考虑到是无向图,对于每一个 edge 我们需要在两个 list 中更新才行。然后维护一个 HashMap<> 存着每一个 height 对应的 List<>,然后循环扫描每一个点作为起点进行 BFS,找到最小 height 之后 map.get(height) 就可以了。

然而这种做法的时间复杂度是 O(V * (E + V)) ,每个点都要扫整个 graph ,太高了。

转换一下思路,我们做的事情其实非常近似于 , 对于一个形状和链表一样的图,我们知道最优解一定是中点;对于一个 inorder traversal array,我们知道 height balanced tree 也一定以中点为 root;

  • 在这个 graph 里,我们要找的,其实也是一层一层剥开最外围 nodes 之后,最里面的点。

因此,即使是 undirected graph,degree 也是非常重要的信息,只不过对于 undirected graph 来讲:

  • degree = "in"-degree + "out"-degree 而已.

AC代码,速度击败了 95.98 % ~

O(E + V)

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        int[] degrees = new int[n];
        ArrayList[] graph = new ArrayList[n];

        for(int i = 0; i < n; i++){
            graph[i] = new ArrayList<>();
        }

        for(int[] edge : edges){
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
            degrees[edge[0]]++;
            degrees[edge[1]]++;
        }

        Queue<Integer> queue = new LinkedList<Integer>();
        for(int i = 0; i < n; i++){
            if(degrees[i] <= 1) queue.offer(i);
        }

        List<Integer> list = new ArrayList<>();
        while(!queue.isEmpty()){
            int size = queue.size();
            list = new ArrayList<>();
            for(int i = 0; i < size; i++){
                int node = queue.poll();
                list.add(node);
                for(int j = 0; j < graph[node].size(); j++){
                    int next = (int)graph[node].get(j);
                    degrees[next] --;
                    if(degrees[next] == 1) queue.offer(next);
                }
            }
        }

        return list;
    }
}

这题我之前写 union-find 的时候做过了,确实是更快更高效的写法。不过这题也完全可以用 Graph 上的常规 BFS / DFS 求解.

这题用 BFS 解需要解决这么几个问题:

  • 如何正确 detect cycle?

    • 常规 indegree 的话,如果有 cycle 会有一些点因为 indegree 无法进一步缩小的问题永远不被访问,可以记录 visited count;

    • 另一种方法是,用 int[] 表示每个点的状态,其中

      • 0 代表“未访问”;

      • 1 代表“访问中”;

      • 2 代表“已访问”;

    • 如果在循环的任何时刻,我们试图访问一个状态为 “1” 的节点,都可以说明图中有环。

  • 如何正确识别图中 connected components 的数量?

    • 添加任意点,探索所有能到达的点,探索完毕数量 +1;

    • 如此往复,直到已探索点的数量 = # of V in graph 为止。

BFS 做法,时间复杂度 O(E + V);

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        int[] states = new int[n];
        ArrayList[] graph = new ArrayList[n];

        for(int i = 0; i < n; i++){
            graph[i] = new ArrayList();
        }

        for(int[] edge : edges){
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
        }

        Queue<Integer> queue = new LinkedList<>();

        queue.offer(0); 
        states[0] = 1;
        int count = 0;

        while(!queue.isEmpty()){
            int node = queue.poll();
            count ++;
            for(int i = 0; i < graph[node].size(); i++){
                int next = (int) graph[node].get(i);

                if(states[next] == 1) return false ;
                else if(states[next] == 0){
                    states[next] = 1;
                    queue.offer(next);
                }
            }
            states[node] = 2;
        }

        return count == n;
    }
}

一次 AC ~ 由于不用考虑环和拓扑顺序,BFS 的方式就很简单,记录下看过哪些点就可以了。

参考了下论坛讨论之后,不太同意大多数解法,因为假设所有点的 label 唯一不是很适合 generalize 这个算法。用 HashMap<> 实现 Node - Node mapping 比较靠谱。

下面的代码简化了一下,参考了九章的写法,先用一个 getNodes 函数返回所有的节点(因为函数就给了一个),在返回的时候直接 new ArrayList<>(set) 调用 Collection constructor.

这样算法逻辑就分成两步:

  • 过一遍所有节点,建新节点放到 HashMap 中;

  • 再过一遍所有节点,这次更新每个对应节点的 neighbors.

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return node;

        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();

        List<UndirectedGraphNode> nodeList = getNodes(node);

        for(UndirectedGraphNode cur : nodeList){
            map.put(cur, new UndirectedGraphNode(cur.label));
        }

        for(UndirectedGraphNode cur : nodeList){
            UndirectedGraphNode copy = map.get(cur);

            for(UndirectedGraphNode neighbor : cur.neighbors){
                copy.neighbors.add(map.get(neighbor));
            }
        }

        return map.get(node);
    }

    private List<UndirectedGraphNode> getNodes(UndirectedGraphNode node){
        Set<UndirectedGraphNode> visited = new HashSet<>();
        Queue<UndirectedGraphNode> queue = new LinkedList<>();

        queue.offer(node);
        visited.add(node);

        while(!queue.isEmpty()){
            UndirectedGraphNode cur = queue.poll();
            for(UndirectedGraphNode next : cur.neighbors){
                if(!visited.contains(next)){
                    visited.add(next);
                    queue.offer(next);
                }
            }
        }

        return new ArrayList<>(visited);
    }
}

链表也是图啊,就是这么简单,轻松,愉快~~

这题还有一个比较妖孽的 follow-up,不让用 HashMap. 做法就是在每个节点后面插入新节点,最后再拆出来就行了,复杂度依然 O(n).

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        HashMap<RandomListNode, RandomListNode> map = new HashMap<>();

        RandomListNode cur;

        for(cur = head; cur != null; cur = cur.next){
            map.put(cur, new RandomListNode(cur.label));
        }

        for(cur = head; cur != null; cur = cur.next){
            RandomListNode copy = map.get(cur);

            copy.random = map.get(cur.random);
            copy.next = map.get(cur.next);
        }

        return map.get(head);
    }
}

Minimum Height Trees
https://discuss.leetcode.com/topic/30572/share-some-thoughts
Find Leaves of Binary Tree
Graph Valid Tree
一个非常精炼的 BFS, DFS, Union-Find 做法总结帖子
Clone Graph
Copy List with Random Pointer