[Leetcode] [Java] Clone Graph

Source: Internet
Author: User

Title:

Clone an undirected graph. Each node in the graph contains a and label a lists of its neighbors .

OJ ' s undirected graph serialization:

Nodes is labeled uniquely.

We use # as a separator for each node, and as , a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2} .

The Graph has a total of three nodes, and therefore contains three parts as separated by # .

  1. first node is labeled As 0 . Connect node 0  to both Nodes 1  and 2 .
  2. second node is labeled As 1 . Connect node 1  to node 2 .
  3. Third node is labeled as 2 . Connect node 2 to Node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1      /      /       0---2         /          \_/
Test Instructions:

Clones an image without a direction. Each node in the diagram contains one label and a group neighbors .

The definition of the non-direction graph in the subject is:

Each node is uniquely marked.

I Through # to divide each node   through to divide the node tag and each neighbor of the node.

For example, given a figure {0 , 1,2# Span style= "Color:blue" >1 , * 2 , 2}

this A total of 3 nodes in the diagram, thus containing the # Three parts divided by

   1. The first node is marked 0. connection node 0 and node 1  AND  2

   2. The second node is marked   1. node 1 2 Connected.

  3. The third node is marked as   2. node 2 and node 2 (it itself) wants to connect, thus forming a self-loop.

The figure is as follows:

       1      /      /       0---2         /          \_/

Algorithm Analysis:


* A total of two methods, dfs--recursion, bfs--queue

* The Copy method is to use the Hashmap,key to save the original value, value of the copy, the Dfs or BFs method to traverse the value of the Help copy neighbors.

* But here's a question, when cloning a node we need to clone its neighbors, and some of the neighbor nodes already exist, some do not exist, how to differentiate?


* Here we use map to distinguish, the key value of the map is the original node,value for the new clone of node, when the discovery of a node is not in the map when the node has not been clone,


AC Code:
/** * Definition for undirected graph. * Class Undirectedgraphnode  * {*     int label; *     list<undirectedgraphnode> neighbors; *     Undirectedgraphnode (int x) {label = x; neighbors = new arraylist<undirectedgraphnode> ();}}; */


Method One: Breadth First search BFS utilization queue

public class Solution {public Undirectedgraphnode Clonegraph (Undirectedgraphnode node) {if (node = = null)                    return null; Hashmap<undirectedgraphnode, undirectedgraphnode> HM = new Hashmap<undirectedgraphnode, UndirectedGraphNode        > ();        linkedlist<undirectedgraphnode> queue = new linkedlist<undirectedgraphnode> ();        Undirectedgraphnode head = new Undirectedgraphnode (Node.label);                Hm.put (node, head);//key the original value, value Queue.add (node) of the stored copy;            while (!queue.isempty ()) {Undirectedgraphnode Curnode = Queue.poll (); for (Undirectedgraphnode aneighbor:curnode.neighbors)//check each neighbor {if (!hm.containskey (                    Aneighbor))//if not visited,then add to queue {Queue.add (Aneighbor);                    Undirectedgraphnode Newneighbor = new Undirectedgraphnode (Aneighbor.label); Hm.put (Aneighbor, Newneighbor);         } hm.get (Curnode). Neighbors.add (Hm.get (Aneighbor));//head.neighbors.add (Newneightbor)}}    return head; }}

Method Two: Dfs depth-first traversal via recursion

public class Solution {public Undirectedgraphnode Clonegraph (Undirectedgraphnode node) {if (node = = nul                            L) return null; Hashmap<undirectedgraphnode, undirectedgraphnode> HM = new Hashmap<undirectedgraphnode, UndirectedGraphNode            > (); Undirectedgraphnode head = new Undirectedgraphnode (Node.label);//Initialize session node without adjacency node Hm.put (node, head);//key Save original value, Val    The value of the UE save copy DFS (HM, node);//dfs return head; } public void DFS (Hashmap<undirectedgraphnode, undirectedgraphnode> hm, Undirectedgraphnode node) {if (                    node = = null) return;                for (Undirectedgraphnode aneighbor:node.neighbors) {if (!hm.containskey (Aneighbor)) {                Undirectedgraphnode Newneighbor = new Undirectedgraphnode (Aneighbor.label);                Hm.put (Aneighbor, Newneighbor);   DFS (HM, Aneighbor);//dfs}         Hm.get (node). Neighbors.add (Hm.get (Aneighbor));//Copy neighbors value to the node. }    }}

Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Clone Graph

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.