0

我正在尝试为和谐的图形着色编写回溯算法(相邻颜色不能相同,并且每对颜色只能出现一次)。这是回溯功能:

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 <--- 这是错误的

1 7 3 0 <--- 这也是错误的

因此,当它在当前树中找不到解决方案时,它只会结束一切而不是向上。为什么会这样?

4

0 回答 0