Ejemplo n.º 1
0
        public static bool hasPathBfs(GraphNode n, GraphNode search)
        {
            Queue<GraphNode> nodeQueue = new Queue<GraphNode>();
            HashSet<GraphNode> visited = new HashSet<GraphNode>();

            nodeQueue.Enqueue(n);
            visited.Add(n);

            while (nodeQueue.Count != 0)
            {
                GraphNode currNode = nodeQueue.Dequeue();
                if (currNode == search)
                {
                    return true;
                }
                foreach (GraphNode node in currNode.Neighbors)
                {
                    if (!visited.Contains(node))
                    {
                        nodeQueue.Enqueue(node);
                        visited.Add(node);
                    }
                }
            }

            return false;
        }
Ejemplo n.º 2
0
        public static bool hasPathDfs(GraphNode n, GraphNode search, HashSet<GraphNode> visited)
        {
            if (n == search)
            {
                return true;
            }

            visited.Add(n);
            foreach (GraphNode node in n.Neighbors)
            {
                if (!visited.Contains(node))
                {
                    bool result = hasPathDfs(node, search, visited);
                    if (result)
                    {
                        return true;
                    }
                }
            }

            return false;
        }