LeetCode Clone Graph (golang&java)

本文介绍了图的基本概念,包括无环树和有向无环图(DAG),并详细阐述了邻接列表和邻接矩阵两种表示图的方法。接着,文章讲述了在解决LeetCode克隆图问题时,如何使用HashMap、队列进行深度优先搜索(DFS)和广度优先搜索(BFS)。最后,提供了Go和Java两种语言的克隆图代码实现。
摘要由CSDN通过智能技术生成

Problem
在这里插入图片描述
在这里插入图片描述
Basics
Graph
In computer science, a graph is defined as a set of vertices paired with a set of edges. The vertices are represented by circles, and the edges are the lines between them. Edges connect a vertex to other vertices.

The following are also graphs:
Tree and linked list
On the left is a tree structure, on the right a linked list. They can be considered graphs but in a simpler form. They both have
vertices (nodes) and edges (links).
The first graph includes cycles, where you can start off at a vertex, follow a path, and come back to the original vertex. A tree is a graph without such cycles.
Another common type of graph is the directed acyclic graph or DAG:
DAG
Like a tree, this graph does not have any cycles (no matter where you start, there is no path back to the starting vertex), but this graph has directional edges with the shape that does not necessarily form a hierarchy.

Adjacency list
The adjacency list describes outgoing edges. A has an edge to B, but B does not have an edge back to A, so A does not appear in B’s adjacency list. Finding an edge or weight between two vertices can be expensive because there is no random access to edges. You must traverse the adjacency lists until it is found.

Adjacency Matrix.
In an adjacency matrix implementation, a matrix with rows and columns representing vertices stores a weight to indicate if vertices are connected and by what weight.

Analysis Process
1.HashMap is used to store all the visited nodes and the key of the clone node HashMap to store the nodes of the original graph. Value stores the corresponding nodes in the clone diagram to prevent them from falling into a dead loop, and to obtain the nodes of the clone graph
2.Add the first node to the queue clone add the first node to the HashMap named Visited
3.BFS
Fetch a node from the head of the queue
Traverses all of the nodes’ adjacencies
If an adjacent point has been visited, the adjacent point must be in visited, then the adjacent point is obtained from visited
Otherwise, create a new node to store in visited
Adds the cloned adjacency point to the adjacency list of the corresponding node in the clone diagram

Code
golang

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Neighbors []*Node
 * }
 */

func cloneGraph(node *Node) *Node {
   if node == nil {
      return node
   }
   // use bfs algorithm to traverse the graph and get all nodes.
   nodes := getNodes(node)
   // copy nodes, store the old->new mapping information in a hash map
   mapping := make(map[*Node]*Node)
   for _, n := range nodes {
      mapping[n] = &Node{Val: n.Val}
   }
   // copy neighbors(edges)
   for _, n := range nodes {
      newNode := mapping[n]
      for _, neighbor := range n.Neighbors {
         newNeighbor := mapping[neighbor]
         newNode.Neighbors = append(newNode.Neighbors, newNeighbor)
      }
   }
   return mapping[node]
}

func getNodes(node *Node) []*Node {
   var queue []*Node
   set := make(map[*Node]bool)
   queue = append(queue, node)
   set[node] = true
   for len(queue) > 0 {
      head := queue[0]
      queue = queue[1:]
      for _, neighbor := range head.Neighbors {
         if _, ok := set[neighbor]; !ok {
            set[neighbor] = true
            queue = append(queue, neighbor)
         }
      }
   }
   var res []*Node
   for k := range set {
      res = append(res, k)
   }
   return res
}

java

class Solution {
    public Node cloneGraph(Node node) {
        if(node == null) return null;
        Map<Node, List<Node>> graph = new HashMap<>();//use map to store figure
        List<Node> v = new ArrayList<>();//bfs
        v.add(node);
        graph.put(node, node.neighbors);
        while(!v.isEmpty()){
            Node p = v.get(0);
            v.remove(0);
            for(Node i : p.neighbors){
                if(!graph.containsKey(i)){
                    v.add(i);
                    graph.put(i, i.neighbors);
                }
            }
        }
        List<Node> vec = new ArrayList<>(graph.keySet());//Gets all nodes of the old diagram
        int k = vec.indexOf(node);
        List<Node> r = new ArrayList<>();//Copy the new image using the subscript of the old one
        for(int i = 0; i < vec.size(); ++i) r.add(new Node(vec.get(i).val));
        for(int i = 0; i < vec.size(); ++i){
            for(int j = 0; j < vec.get(i).neighbors.size(); ++j){
                r.get(i).neighbors.add(r.get(vec.indexOf(vec.get(i).neighbors.get(j))));
            }
        }
        return r.get(k);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值