我正在尝试为和谐图形着色编写回溯算法(没有相邻的颜色可以是相同的,并且每对颜色也只能出现一次)。 这是回溯功能:
void Graph::colorBacktrack(int a, int b) {
print();
for (int i = 1; i <= colors; i++) //assigning colors until match
{
elems[a][b] = i; //color
if (check(a, b)) break; //if it's alright break
if (i == colors) // if all the colors have been used -
return; //return one stack back and look again
}
int nextA;
int nextB = b;
if (a < size - 1 ) nextA = a + 1;
else {
nextA = 0;
nextB = b + 1;
}
if (a == size && b == size - 1) //when array is complete - cout finished
{
cout << endl << endl << "Finished" << endl << endl;
}
colorBacktrack(nextA, nextB); //go to next node when everything is fine
}
检查工作正常以及所有其他事情。问题是输出是错误的 - 最后它显示如下:
1 4 2 6
2 5 7 8
3 6 4 8 &lt; ---这是错误的
1 7 3 0 &lt; ---这也是错误的
因此,当它无法在当前树中找到解决方案时,它只会结束所有内容而不是上升。为什么会这样?