DFS探索のつもり。
再帰使いたくなかったので、再帰使わないDFS探索。
クラス使ったやり方のがいいのかもしれないけど、よく分からなかったのでとりあえず。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sanc
{
class Program
{
private static int _Idx;
public static int Idx
{
get => _Idx;
set
{
_Idx = value;
Console.WriteLine(value);
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var ExeTree = new Dictionary<int, List<int>>();
ExeTree.Add(1, new List<int>() { 2, 3});
ExeTree.Add(2, new List<int>() { 6 });
ExeTree.Add(3, new List<int>() { 4, 5, 7});
ExeTree.Add(4, new List<int>() { 8, 9 });
ExeTree.Add(7, new List<int>() { 10 });
//A⇒Bを記録
var MemoryPlace = new List<KeyValuePair<int, int>>();
Idx = 1;
var LastIdxes = new List<int>() { 1 };
int LastIdx;
while (LastIdxes.Any())
{
while (ExeTree.ContainsKey(Idx))
{
var LastIdxInLoop = Idx;
var Values = ExeTree[Idx];
foreach(var Value in Values)
{
//行ったことある道でなければif内実行
if(!MemoryPlace.Contains(new KeyValuePair<int, int>(Idx, Value)))
{
MemoryPlace.Add(new KeyValuePair<int, int>(Idx, Value));
Idx = Value;
LastIdxes.Add(Idx);
break;
}
}
//変更があればもう一回ループ.
//なければIdxに対して全て行ったValueなのでbreakで抜ける.
if (LastIdxInLoop == Idx) break;
}
if (LastIdxes.Count > 1)
{
LastIdx = LastIdxes.SkipLast(1).Last();
LastIdxes.Remove(LastIdxes.Last());
Idx = LastIdx;
}
else if(LastIdxes.Count == 1)
{
break;
}
}
}
}
}