-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForest.cs
More file actions
95 lines (83 loc) · 2.2 KB
/
Forest.cs
File metadata and controls
95 lines (83 loc) · 2.2 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using ImageQuantization;
using System.Collections.Generic;
class Forest
{
static Dictionary<int, List<int>> Trees;
public Forest(List<Edge> Edges) //O(D-K)
{
Trees = new Dictionary<int, List<int>>();
foreach (Edge edge in Edges) //O(D-K)
{
AddEdge(edge.from, edge.to); //O(1)
AddEdge(edge.to, edge.from); //O(1)
}
}
private void AddEdge(int a, int b)
{
if (Trees.ContainsKey(a))
{
List<int> l = Trees[a];
l.Add(b);
if (Trees.ContainsKey(a))
Trees[a] = l;
else
Trees.Add(a, l);
}
else
{
List<int> l = new List<int>();
l.Add(b);
Trees.Add(a, l);
}
}
public static List<RGBPixel> BFS(int s, List<bool> visited)
{
List<RGBPixel> cluster = new List<RGBPixel>();
List<int> q = new List<int>();
q.Add(s);
visited.RemoveAt(s);
visited.Insert(s, true);
while (q.Count != 0)
{
int f = q[0];
q.RemoveAt(0);
cluster.Add(IToPixel(f));
if (Trees.ContainsKey(f))
{
foreach (int iN in Trees[f])
{
int n = iN;
if (!visited[n])
{
visited.RemoveAt(n);
visited.Insert(n, true);
q.Add(n);
}
}
}
}
return cluster;
}
private static RGBPixel IToPixel(int index)
{
return RGBPixel.UnHash(ColorQuantization.distinctColorsList[index]);
}
public static List<List<RGBPixel>> GetClusters(int V)
{
List<bool> visited = new List<bool>();
List<List<RGBPixel>> clusters = new List<List<RGBPixel>>();
for (int i = 0; i < V; i++)
{
visited.Insert(i, false);
}
for (int i = 0; i < V; i++)
{
if (!visited[i])
{
var cluster = BFS(i, visited);
clusters.Add(cluster);
}
}
return clusters;
}
}