Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 3, 2016 23:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jianminchen/c328dbc4391cb03a9ab8665b3ab54966 to your computer and use it in GitHub Desktop.
Save jianminchen/c328dbc4391cb03a9ab8665b3ab54966 to your computer and use it in GitHub Desktop.
Leetcode 133 - Clone Graph - C# solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cloneGraph
{
/*
* source code from web blog:
* http://www.programcreek.com/2012/12/leetcode-clone-graph-java/
*
* Leetcode Clone Graph
*
* http://www.cnblogs.com/springfor/p/3874591.html
*
*/
/**
Definition for undirected graph.
*/
// Undirected Graph Node - Node
class Node
{
public int label;
public List<Node> neighbors;
public Node(int x)
{
label = x;
neighbors = new List<Node>();
}
}
class Program
{
static void Main(string[] args)
{
// {0, 1, 2#1, 2#2, 2}
Node node0 = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
List<Node> list0 = new List<Node>();
list0.Add(node1);
list0.Add(node2);
node0.neighbors = list0;
node1.neighbors = new List<Node>();
node1.neighbors.Add(node2);
node2.neighbors = new List<Node>();
node2.neighbors.Add(node2);
Node newClone = cloneGraph(node0);
Node newClone2 = cloneGraph(node1);
Node newClone3 = cloneGraph(node2);
}
/*
* Quickly go over the code with test case
*
*/
public static Node cloneGraph(Node node) {
if(node == null)
return null;
Queue<Node> queue = new Queue<Node>();
Dictionary<Node, Node> map =
new Dictionary<Node,Node>();
Node newHead = new Node(node.label);
queue.Enqueue(node);
map.Add(node, newHead);
while(queue.Count > 0 ){
Node curr = (Node)queue.Dequeue();
List<Node> currNeighbors = curr.neighbors;
foreach (Node aNeighbor in currNeighbors){
if(!map.ContainsKey(aNeighbor)){
Node copy = new Node(aNeighbor.label);
map.Add(aNeighbor,copy);
map[curr].neighbors.Add(copy);
queue.Enqueue(aNeighbor);
}else{
map[curr].neighbors.Add(map[aNeighbor]);
}
}
}
return newHead;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment