コード例 #1
0
bool Graph::SearchDFS(GraphNode* start, GraphNode* end)
{
	ResetVisited();

	std::stack<GraphNode*> nodeStack;
	nodeStack.push(start);

	//keep looping until the stack is empty. 
	//This will only happen once we've checked every node. 
	while (!nodeStack.empty())
	{
		//the rest of the algorithm goes in here
		GraphNode* current = nodeStack.top();
		nodeStack.pop();

		if (!current->GetIsVisited())
		{
			current->SetIsVisited(true);

			if (current == end)
			{
				return true;
			}

			for (int i = 0; i < int(current->GetEdgeList().size()); ++i)
			{
				nodeStack.push(current->GetEdgeList()[i]->GetEnd());
			}
		}
		return false;
	}

	return false;
}
コード例 #2
0
bool Graph::SearchBFS(GraphNode* start, GraphNode* end)
{
	ResetVisited();

	std::queue<GraphNode*> nodeQueue;
	nodeQueue.push(start);

	//keep looping until the stack is empty. 
	//This will only happen once we've checked every node. 
	while (!nodeQueue.empty())
	{
		GraphNode* current = nodeQueue.front();

		if (!current->GetIsVisited())
		{
			current->SetIsVisited(true);

			if (current == end)
			{
				return true;
			}

			for (int i = 0; i < int(current->GetEdgeList().size()); ++i)
			{
				nodeQueue.push(current->GetEdgeList()[i]->GetEnd());
			}
		}

		nodeQueue.pop();

		return false;
	}

	return false;
}