zoukankan      html  css  js  c++  java
  • [Algo] 132. Deep Copy Undirected Graph

    Make a deep copy of an undirected graph, there could be cycles in the original graph.

    Assumptions

    • The given graph is not null

    DFS

    /*
    * class GraphNode {
    *   public int key;
    *   public List<GraphNode> neighbors;
    *   public GraphNode(int key) {
    *     this.key = key;
    *     this.neighbors = new ArrayList<GraphNode>();
    *   }
    * }
    */
    public class Solution {
      public List<GraphNode> copy(List<GraphNode> graph) {
        // Write your solution here.
        Map<GraphNode, GraphNode> map = new HashMap<>();
        for (GraphNode node : graph) {
          if (!map.containsKey(node)) {
            map.put(node, new GraphNode(node.key));
          }
          dfs(node, map);
        }
        return new ArrayList<>(map.values());
      }
    
      private void dfs(GraphNode node, Map<GraphNode, GraphNode> map) {
        GraphNode newNode = map.get(node);
        for (GraphNode gNode : node.neighbors) {
          if (!map.containsKey(gNode)) {
            map.put(gNode, new GraphNode(gNode.key));
          }
          newNode.neighbors.add(map.get(gNode));
        }
      }
    }

    BFS

    /*
    * class GraphNode {
    *   public int key;
    *   public List<GraphNode> neighbors;
    *   public GraphNode(int key) {
    *     this.key = key;
    *     this.neighbors = new ArrayList<GraphNode>();
    *   }
    * }
    */
    public class Solution {
      public List<GraphNode> copy(List<GraphNode> graph) {
        // Write your solution here.
        Map<GraphNode, GraphNode> map = new HashMap<>();
        for (GraphNode gNode: graph) {
          map.put(gNode, new GraphNode(gNode.key));
        }
        for (GraphNode node : graph) {
          GraphNode cpNode = map.get(node);
          for (GraphNode nei: node.neighbors) {
            cpNode.neighbors.add(map.get(nei));
          }
        }
        return new ArrayList<>(map.values());
      }
    }
  • 相关阅读:
    Rebots协议是什么?
    Requests库入门
    jieba库的使用及实例
    第六周 python组合数据类型
    python 有基础入门程序
    字符与字符串操作归纳[持续更新]
    C++调用bat并实现传值
    Python如何运行程序
    Execl数据上传到数据库
    xml 文件操作
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12366061.html
Copyright © 2011-2022 走看看