-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.cs
More file actions
81 lines (74 loc) · 1.53 KB
/
CloneGraph.cs
File metadata and controls
81 lines (74 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
// Definition for a Node.
public class Node {
public int val;
public IList<Node> neighbors;
public Node(){}
public Node(int _val,IList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
*/
public class Solution
{
public Node CloneGraph(Node node)
{
var dict = new Dictonary<Node, Node>();
var clone = new Node(node.val, node.neighbors)
dict.Add(node, clone);
var q = Queue<Node>();
//var set = new MyNode(q);
q.Add(node);
while (!q.IsEmpty())
{
Node n = q.Dequeue();
foreach (var n in q.neighbors)
{
if (!dict.Contains(n))
{
dict.Add(n, new Node(n.val, ))
}
}
}
}
public MyNode Find(MyNode node)
{
if (node.parent != node)
{
node.parent = Find(node);
}
return node.parent;
}
public void Union(MyNode p, MyNode c)
{
var pRoot = Find(p);
var cRoot = Find(c);
if (pRoot == cRoot)
{
return;
}
if (pRoot.rank < cRoot.rank)
{
var swap = p;
p = c;
c = p;
}
cRoot.parent = pRoot;
if (pRoot.rank == cRoot.rank)
{
pRoot.rank++;
}
}
}
public class MyNode
{
Node value;
int rank;
MyNode parent;
MyNode(Node value)
{
value = value;
rank = 0;
parent = value;
}
}