0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

資料d

Posted at

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


    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?