4 - BFS & Topological Algorithm

Posted jenna

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4 - BFS & Topological Algorithm相关的知识,希望对你有一定的参考价值。

 

127. Topological Sorting

https://www.lintcode.com/problem/topological-sorting/description?_from=ladder&&fromId=1

1. 用Map来存储入度。可以用数组来存吗?不可以。

Map<DirectedGraphNode, Integer> map,为什么要用map来存而不是数组来存呢?因为数组记录的都是Integer

2. 将入度为0的结点压入 queue 中。同时,将入度为0的结点存到result里

3. 遍历queue中的元素,遍历元素的neighbor,把对应 neighbor 的入度减一。当入度为0,将结点存到 result 里。

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */

public class Solution {
    /*
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        ArrayList<DirectedGraphNode> result = new ArrayList<>();
        Map<DirectedGraphNode, Integer> map = new HashMap<>();
        for(DirectedGraphNode node: graph) {
            for(DirectedGraphNode neighbor: node.neighbors) {
                if(map.containsKey(neighbor)) {
                    map.put(neighbor, map.get(neighbor) + 1);
                } else {
                    map.put(neighbor, 1);
                }
            }
        }
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        for(DirectedGraphNode node: graph) {
            if(!map.containsKey(node)) {
                queue.offer(node);
                result.add(node);
            }
        }
        while(!queue.isEmpty()) {
            DirectedGraphNode curr = queue.poll();
            for(DirectedGraphNode neighbor: curr.neighbors) {
                map.put(neighbor, map.get(neighbor) - 1);
                if(map.get(neighbor) == 0) {
                    queue.offer(neighbor);
                    result.add(neighbor);
                }
            }
        }
        return result;
    }
}

7. Serialize and Deserialize Binary Tree

https://www.lintcode.com/problem/serialize-and-deserialize-binary-tree/description?_from=ladder&&fromId=1

Serialize:

1. 从根结点开始,将所有的左孩子,右孩子以及叶子结点,压入queue中。

2. 从queue中移除一些不需要存储的元素。

3. 进行append操作

Deserialize:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    public String serialize(TreeNode root) {
        // write your code here
        if(root == null) {
            return "{}";
        }
        ArrayList<TreeNode> queue = new ArrayList<>();
        queue.add(root);
        for(int i = 0; i < queue.size(); i++) {
            TreeNode curr = queue.get(i);
            if(curr == null) {
                continue;
            }
            queue.add(curr.left);
            queue.add(curr.right);
        }
        while(queue.get(queue.size() - 1) == null) {
            queue.remove(queue.size() - 1);
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(queue.get(0).val);
        for(int i = 1; i < queue.size(); i++) {
            TreeNode curr = queue.get(i);
            if(curr == null) {
                sb.append(",#");
            } else {
                sb.append(",");
                sb.append(curr.val);
            }
        }
        sb.append("}");
        return sb.toString();
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it‘s given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
        // write your code here
        if(data.equals("{}")) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        ArrayList<TreeNode> queue = new ArrayList<>();
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        queue.add(root);
        int index = 0;
        boolean isLeftChild = true;
        for(int i = 1; i < vals.length; i++) {
            if(!vals[i].equals("#")) {
                TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
                if(isLeftChild) {
                    queue.get(index).left = node;
                } else {
                    queue.get(index).right = node;
                }
                queue.add(node);
            }
            if(!isLeftChild) {
                index++;
            }
            isLeftChild =  !isLeftChild;
        }
        return root;
    }
}

 

以上是关于4 - BFS & Topological Algorithm的主要内容,如果未能解决你的问题,请参考以下文章

Topological Sort

USACO 4.4 Frame up Topological Sort

UVa 1601 || POJ 3523 The Morning after Halloween (BFS || 双向BFS && 降维 && 状压)

BFS & DFS

bfs输出路径 && 最短路(迪杰斯特拉)输出路径

Topological Sort