-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution433.cs
72 lines (60 loc) · 1.78 KB
/
Solution433.cs
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
namespace LeetCode.Solutions;
public class Solution433
{
/// <summary>
/// 433. Minimum Genetic Mutation - Medium
/// <a href="https://leetcode.com/problems/minimum-genetic-mutation">See the problem</a>
/// </summary>
public int MinMutation(string startGene, string endGene, string[] bank)
{
var bankSet = new HashSet<string>(bank);
if (!bankSet.Contains(endGene))
{
return -1;
}
var queue = new Queue<string>();
queue.Enqueue(startGene);
var mutations = 0;
while (queue.Count > 0)
{
var size = queue.Count;
for (var i = 0; i < size; i++)
{
var current = queue.Dequeue();
if (current == endGene)
{
return mutations;
}
foreach (var next in GetNextMutations(current, bankSet))
{
queue.Enqueue(next);
}
}
mutations++;
}
return -1;
}
private IEnumerable<string> GetNextMutations(string current, HashSet<string> bank)
{
var mutations = new List<string>();
var chars = new[] { 'A', 'C', 'G', 'T' };
foreach (var i in Enumerable.Range(0, current.Length))
{
foreach (var c in chars)
{
if (current[i] == c)
{
continue;
}
var mutation = current[..i] + c + current[(i + 1)..];
if (!bank.Contains(mutation))
{
continue;
}
bank.Remove(mutation);
mutations.Add(mutation);
}
}
return mutations;
}
}