From 4b43fceae9ddd09310bf9c5d7106963bcedb069f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 28 Apr 2024 00:36:07 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB514.=20Freedom=20Trail=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/freedom-trail.cs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 cs/freedom-trail.cs diff --git a/cs/freedom-trail.cs b/cs/freedom-trail.cs new file mode 100644 index 0000000..0efceb4 --- /dev/null +++ b/cs/freedom-trail.cs @@ -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]; + } +}