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; } }