Ejemplo n.º 1
0
// Backtrack Algorithm
bool ColorationEngine::backtrackAlgorithm(unsigned int nbColors)
{
	// On commence par vider la pile, au cas où elle ne le serait pas déjà
	while (!this->verticesStack.empty())
	{
		this->verticesStack.pop();
	}


	// Liste de toutes les couleurs dispo
	std::set<unsigned int> colors;
	for (unsigned int i = 1; i <= nbColors; ++i)
	{
		colors.insert(i);
	}

	// Initialisation du domaine de couleurs de chaque sommet
	// puis ajout des sommets dans la pile (ordre quelconque)
	for (unsigned int i = 0; i < this->verticesSet.size() ; ++i)
	{
		verticesSet[i]->setAvailableColors(colors);
		this->verticesStack.push(this->verticesSet[i]);
	}

	// Liste des sommets traités
	std::stack<Vertex*> result = std::stack<Vertex*>();

	int currentColor = 0;

	Vertex* currentVertex = verticesStack.top();
	verticesStack.pop();
	currentColor = currentVertex->getNextAvailableColor();
	currentVertex->setColor(currentColor);
	result.push(currentVertex);

	bool test = true;

	currentVertex = verticesStack.top();
	std::set<unsigned int> currentColors = currentVertex->getAvailableColors();

	while (test) {

		currentColor = currentVertex->getNextAvailableColor();
		if (currentColor != 0)
		{
			if (!currentVertex->are_neighbors_colored(currentColor))
			{
				verticesStack.pop();
				currentVertex->setColor(currentColor);
				result.push(currentVertex);
				currentVertex->setAvailableColors(currentColors);

				if (verticesStack.empty())
				{
					test = false; // solution trouvée
				}
				else
				{
					currentVertex = verticesStack.top();
					currentColors = currentVertex->getAvailableColors();
				}
			}
			else
			{
				currentColors.erase(currentColor);
				currentVertex->removeAvailableColor(currentColor);
			}
		}
		else
		{
			verticesStack.push(currentVertex);
			if (!result.empty()) {
				currentVertex = result.top();
				result.pop();
			} else {
				break;
			}

			currentVertex->removeAvailableColor(currentVertex->getColor());
			currentColors = currentVertex->getAvailableColors();
			currentVertex->setColor(0);
		}
	}

	if (result.empty())
	{
		std::cout << "pas de solution" << std::endl;
		return false;
	}
	else
	{
		std::cout << "solution trouvée" << std::endl;
		return true;
	}
}