Some of the code has been omitted. I am trying to write a DFS function to traverse a maze. It will eventualy add the nodes to a tree that I will traverse once I get the DFS working. Currently it goes into an infinite loop and I cannot figure out why. I based it off of this puedo-code

dfs(graph G)
{
  list L = empty
  tree T = empty
  choose a starting vertex x
  search(x)
  while(L is not empty)
  {
    remove edge (v, w) from beginning of L
    if w not yet visited
    {
      add (v, w) to T
      search(w)
    }
  }
}
   
search(vertex v)
{
  visit v
  for each edge (v, w)
    add edge (v, w) to the beginning of L
}

Any help would be so much appreciated I cannot figure this out for the life of me.

vector<Node*> nodeList;//list of verticies
stack<Edge> L;

void search(Node n) {
		n.makeVisited();
		vector<Edge> edges = n.getAdjNodeList();
		for(int i = 0; i < edges.size(); i++) {
			L.push(edges[i]);
			edges.erase(edges.begin()+i);
		}
	}
	
	void DFS(Node start) {
		search(start);
		while(!L.empty()) {
			cerr << "L ISNT EMPTY ";
			Edge ed = Edge(L.top().getNode1(), L.top().getNode2());
			L.pop();
			if((ed.getNode2()->isVisited()) == false) {
				//tree.insertAfter(*ed.getNode1(), *ed.getNode2());
				search(*ed.getNode2());
			} else
				return;
		}
	}

Thanks

Ok Ive tried a new approach to this and this one goes into an infinite loop as well but I was able to figure out that this one keeps going back and fourth between node 0 and node 1 never progressing past that.

If anyone has any idea of whats wrong on either one please let me know

Node DFS(Node n) {
		if(!n.isVisited()) {
			cerr << "Node being visited: " <<  n.getName() << endl;
			n.makeVisited();
			if(n.isEqual(getDestination()))
					return n;	
			while(n.thereAreAdjNodes()) {
				return DFS(n.getUnvisitedAdjNode());
			}
		} else
			return;
	}

These are two of the funcitons that I use which are members of the node class

int name;

vector<Edge> adjNodeList;//list of outgoing edges for this vertex
bool visited;

bool thereAreAdjNodes() {		//checks to see if there is an unvisited node
		for(int i=0; i<adjNodeList.size(); i++) {
			if(adjNodeList[i].getNode2()->isVisited() == false)
				return true;
		}
		return false;			
	}
	
	Node getUnvisitedAdjNode() { 		//returns the first unvisited node of the adjacent lists
		for(int i=0; i<adjNodeList.size(); i++) {
			if(adjNodeList[i].getNode2()->isVisited() == false)
				return *adjNodeList[i].getNode2();
		}
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.