using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int AnswerCnt = int.MinValue; foreach (List<int> EachJyunretuList in DeriveJyunretuListEnum()) { int ChangeCnt = 0; List<int> wkList = new List<int>(EachJyunretuList); int FirstNum = wkList[0]; while (FirstNum != 1) { int[] wkArr = wkList.Take(FirstNum).Reverse().ToArray(); wkList.RemoveRange(0, FirstNum); wkList.InsertRange(0, wkArr); ChangeCnt++; FirstNum = wkList[0]; } if (AnswerCnt <= ChangeCnt) { AnswerCnt = ChangeCnt; var sb = new System.Text.StringBuilder(); sb.AppendFormat("並べ替えの回数={0}の解候補を発見。", ChangeCnt); EachJyunretuList.ForEach(X => sb.AppendFormat("{0},", X)); Console.WriteLine(sb.ToString()); } } } struct JyoutaiDef { internal List<int> NumList; } //1から9の順列を列挙 static IEnumerable<List<int>> DeriveJyunretuListEnum() { var stk = new Stack<JyoutaiDef>(); JyoutaiDef WillPush; WillPush.NumList = new List<int>(); stk.Push(WillPush); while (stk.Count > 0) { JyoutaiDef Popped = stk.Pop(); //クリア判定 if (Popped.NumList.Count == 9) { yield return Popped.NumList; continue; } for (int I = 1; I <= 9; I++) { if (Popped.NumList.Contains(I)) continue; WillPush.NumList = new List<int>(Popped.NumList); WillPush.NumList.Add(I); stk.Push(WillPush); } } } }
省略 並べ替えの回数=28の解候補を発見。8,6,1,3,7,2,9,5,4, 並べ替えの回数=28の解候補を発見。8,6,1,2,7,5,9,3,4, 並べ替えの回数=28の解候補を発見。8,6,1,2,3,7,9,5,4, 並べ替えの回数=28の解候補を発見。7,2,9,5,1,6,8,3,4, 並べ替えの回数=30の解候補を発見。6,1,5,9,7,2,8,3,4,
9の階乗は、362880なので、 深さ優先探索で、列挙オブジェクトを返してます。