//Use this to add an edge to the graph. The method will ensure that the //edge passed as a parameter is valid before adding it to the graph. If the //graph is a digraph then a similar edge connecting the nodes in the opposite //direction will be automatically added. public void AddEdge(GraphEdge edge) { //first make sure the from and to nodes exist within the graph Assert.IsTrue((edge.From() < m_iNextNodeIndex) && (edge.To() < m_iNextNodeIndex), "<SparseGraph::AddEdge>: invalid node index" + " edge:" + edge.From() + "->" + edge.To() + " NextNode : " + m_iNextNodeIndex); //make sure both nodes are active before adding the edge if ((m_Nodes[edge.To()].Index() != GraphNode.INVALID_NODE_INDEX) && (m_Nodes[edge.From()].Index() != GraphNode.INVALID_NODE_INDEX)) { //add the edge, first making sure it is unique if (UniqueEdge(edge.From(), edge.To())) { m_Edges[edge.From()].AddLast(edge); } //if the graph is undirected we must add another connection in the opposite //direction if (!m_bDigraph) { //check to make sure the edge is unique before adding if (UniqueEdge(edge.To(), edge.From())) { GraphEdge NewEdge = edge.Clone() as GraphEdge; NewEdge.SetTo(edge.From()); NewEdge.SetFrom(edge.To()); m_Edges[edge.To()].AddLast(NewEdge); } } } }
//this method performs the DFS search private bool Search() { //create a std stack of edges Stack <GraphEdge> stack = new Stack <GraphEdge>(); //create a dummy edge and put on the stack GraphEdge Dummy = new GraphEdge(m_iSource, m_iSource, 0); stack.Push(Dummy); //while there are edges in the stack keep searching while (0 != stack.Count) { //grab the next edge GraphEdge Next = stack.Peek(); //Debug.Log(Next); //chamto test //remove the edge from the stack stack.Pop(); //make a note of the parent of the node this edge points to m_Route[Next.To()] = Next.From(); //put it on the tree. (making sure the dummy edge is not placed on the tree) if (Next != Dummy) { m_SpanningTree.Add(Next); } //and mark it visited m_Visited[Next.To()] = (int)Aid.visited; //if the target has been found the method can return success if (Next.To() == m_iTarget) { return(true); } //push the edges leading from the node this edge points to onto //the stack (provided the edge does not point to a previously //visited node) foreach (GraphEdge pE in m_Graph.GetEdges(Next.To())) { if (m_Visited[pE.To()] == (int)Aid.unvisited) { stack.Push(pE); } } } //no path to target return(false); }