[C#] 打开密码锁解法

static void Main(string[] args){    OpenLock();}private static void OpenLock(){     string[] deadends = new string[] { "1234", "5678" };     int count = OpenLock(deadends, "1235");     Console.WriteLine($"最小步数: {count}");     Console.ReadKey();} /// <summary> /// 打开密码锁 /// </summary> /// <param name="deadends">死亡密码</param> /// <param name="target">目标密码</param> /// <returns></returns> public static int OpenLock(string[] deadends, string target) {     //使用 HashSet 避免有重覆死亡密码     var dead = new HashSet<string>(deadends);           var visited = new HashSet<string>();//访问过清单     var queue = new Queue<string>();          //添加元素     queue.Enqueue("0000");     visited.Add("0000");     int steps = 0;     while (queue.Count > 0)     {         int size = queue.Count;         for (int i = 0; i < size; i++)         {             var current = queue.Dequeue();             if (dead.Contains(current)) continue;             if (current == target) return steps;             foreach (var next in GetNext(current))             {                                     Console.WriteLine($"经过顺序: {next}");                                  /*  初始化: 0000 开始转会如下                     经过顺序: 1000                     经过顺序: 9000                     经过顺序: 0100                     经过顺序: 0900                     经过顺序: 0010                     经过顺序: 0090                     经过顺序: 0001                     经过顺序: 0009                  */                 if (!visited.Contains(next))                 {                     queue.Enqueue(next);                     visited.Add(next);                 }             }         }         steps++;     }     return -1; // 如果无法达到目标 }/// <summary>/// 转盘 每次 +1 -1/// </summary>/// <param name="combination"></param> /// <returns></returns> private static IEnumerable<string> GetNext(string combination) {     char[] chars = combination.ToCharArray();     for (int i = 0; i < 4; i++)     {         char c = chars[i];         chars[i] = c == '9' ? '0' : (char)(c + 1);         yield return new System.String(chars);         chars[i] = c == '0' ? '9' : (char)(c - 1);         yield return new System.String(chars);         chars[i] = c;     } }        

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章