LoginSignup
11
14

More than 5 years have passed since last update.

C#で深さ優先検索(DFS)と幅優先検索(BFS)の実装

Last updated at Posted at 2015-02-09

深さ優先検索

cs
    public class DFS
    {
        public static void Search( Node root )
        {
            if(root == null)
            {
                return;
            }
            Visit(root);
            root.Visited = true;
            if (root.Children != null)
            { 
                foreach (var node in root.Children)
                {
                    if(!node.Visited)
                    {
                        Search(node);
                    }
                }
            }
        }

        private static void Visit(Node root)
        {
            // nop
        }
    }

    public class Node
    {
        public bool Visited { get; set; }

        public Node[] Children { get; set; }
    }

幅優先検索

cs
        public static void Search( Node root )
        {
            var queue = new Queue<Node>();
            root.Visited = true;
            Visit(root);
            queue.Enqueue(root);

            while(queue.Count != 0)
            {
                var current_node = queue.Dequeue();
                if (current_node.Children != null)
                { 
                    foreach (var node in current_node.Children)
                    {
                        if(!node.Visited)
                        {
                            Visit(node);
                            node.Visited = true;
                            queue.Enqueue(node);
                        }
                    }
                }
            }
        }

        private static void Visit(Node root)
        {
            // nop
        }

GitHubにもあげてあります。
https://github.com/Koki-Shimizu/DFS

11
14
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
11
14