cs: add «514. Freedom Trail»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-04-28 00:36:07 +02:00
parent b3f3754634
commit 4b43fceae9
Signed by: mfocko
GPG key ID: 7C47D46246790496

40
cs/freedom-trail.cs Normal file
View file

@ -0,0 +1,40 @@
public class Solution {
private int Steps(int x, int y, int mod) {
var distance = Math.Abs(x - y);
var coDistance = mod - distance;
return Math.Min(distance, coDistance);
}
private void Relax(string ring, string key, int[][] dp, int r, int k) {
for (var c = 0; c < ring.Length; ++c) {
if (ring[c] != key[k]) {
continue;
}
dp[r][k] = Math.Min(
dp[r][k],
1 + Steps(r, c, ring.Length) + dp[c][k + 1]
);
}
}
public int FindRotateSteps(string ring, string key) {
var dp = new int[ring.Length][];
for (var i = 0; i < ring.Length; ++i) {
var ringPosition = new int[key.Length + 1];
Array.Fill(ringPosition, int.MaxValue);
ringPosition[key.Length] = 0;
dp[i] = ringPosition;
}
for (var k = key.Length - 1; k >= 0; --k) {
for (var r = 0; r < ring.Length; ++r) {
Relax(ring, key, dp, r, k);
}
}
return dp[0][0];
}
}