示例#1
0
        private bool DoBFS(int start, int w, int[] edgeTo, bool[] visited)
        {
            Queue <int> queue = new Queue <int>();

            queue.Enqueue(start);

            while (queue.Count > 0)
            {
                int v = queue.Dequeue();

                //mark v as visited
                visited[v] = true;

                if (v == w)
                {
                    return(true);
                }

                //otherwise, keep adding adjacents
                foreach (int adj in graph.Adjecents(v))
                {
                    if (!visited[adj])
                    {
                        edgeTo[adj] = v;
                        queue.Enqueue(adj);
                    }
                }
            }

            return(false);
        }
示例#2
0
        private bool DoDFS(int start, int w, int[] edgeTo, bool[] visited)
        {
            foreach (int v in graph.Adjecents(start))
            {
                if (visited[v])
                {
                    continue;
                }

                //mark v as visited
                visited[v] = true;

                //mark the path
                edgeTo[v] = start;

                if (v == w)
                {
                    return(true);
                }

                //keep checking the path, now starting from v
                if (DoDFS(v, w, edgeTo, visited))
                {
                    return(true);
                }
            }

            return(false);
        }
示例#3
0
        private bool DoDFS(int start, int w, Stack <int> path, bool[] visited)
        {
            foreach (int v in graph.Adjecents(start))
            {
                if (visited[v])
                {
                    continue;
                }

                //mark v as visited
                visited[v] = true;

                //found the destination
                if (v == w)
                {
                    path.Push(v);
                    return(true);
                }

                //add v to this path
                path.Push(v);

                //keep checking the path, now starting from v
                if (DoDFS(v, w, path, visited))
                {
                    return(true);
                }
                else
                {
                    //if not found, remove v from stack
                    path.Pop();
                }
            }

            return(false);
        }