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());
      }
    }
  • 相关阅读:
    Django Rest framework基础使用之Request/Response
    Django Rest framework基础使用之 serializer
    python基础(一)
    python实现本地图片上传到服务区
    开发中遇到的问题记录
    九、xadmin菜单分组管理
    leetcode-7-整数翻转
    leetcode-6-Z 字形变换
    leetcode-5-最长回文子串
    leetcode-3-无重复字符的最长子串
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12366061.html
Copyright © 2011-2022 走看看