我正在为广度优先搜索算法编写代码。在问题上下文中,一个节点被定义为8个整数的数组,可以同时具有正数和负数。据说正数是男性,负数据说是女性。两位数字可以跳舞,如果他们中的一位是男性,另一位是女性,并且它们的绝对值之和是总数。我必须找到排序阵列所需的最短舞数。例如,对于输入1 2 4 -3 5 6 7 8
答案将是1.因为3可以跳舞2,(因为3是女性,2是男性),并且它们的绝对值的总和是5,这是一个素数。所以在3移动到2跳舞之后,数组变成1 2 -3 4 5 6 7 8
这是排序的。但是我的代码出了问题。我添加了评论,以便阅读更容易。这里是我的BFS代码:使用STL映射调试代码
//Took input.
queue <array1> q;
q.push(init);
level[init] = 0;
visited[init] = true;
array1 v;
while(!q.empty()){
array1 u = q.front();
q.pop();
/*
We can view that the digits have an empty space on either side of them.
Arr2 represents it as 0 when it is an empty space where a digit can come, or else the digits value (1 - 8)
*/
int arr2[17] = {0};
//Loading the arr2 array.
for(int i = 0; i < 8; i++){
arr2[2*i + 1] = u.arr[i];
}
for(int i = 1; i < 17; i+=2){
for(int j = 0; j < 17; j+=2){
//This condition checks if the digit arr2[i] can move to arr2[j] by satisfying all the condition stated above.
if((j - 1 >= 0 && arr2[i] * arr2[j-1] < 0 && j != i-1 && j != i+1 && is_prime(abs(arr2[j-1])+abs(arr2[i])))
||(j + 1 < 17 && arr2[i] * arr2[j+1] < 0 && j != i - 1 && j != i + 1 && is_prime(abs(arr2[j+1])+abs(arr2[i])))){
//If it can, then swap the values.
swap(arr2[j],arr2[i]);
int l = 0;
for(int k = 0; k < 17; k++){
if(arr2[k] == 0) continue;
v.arr[l++] = arr2[k];
}
// v now holds the new state (or array/node)
if(visited[v] == false){
visited[v] = true;
printf("visited[v]: %d\n",visited[v]); // the error is shown here. It prints visited[v] as 0. But I assigned it as true just before this line. Nothing else happened. Why it is 0?
v.print();
level[v] = level[u] + 1;
q.push(v);
if(v.is_sorted()){
while(!q.empty()) q.pop();
ans = level[v];
i = j = 100000; break;
}
}
}
}
}
}
,这里是我的阵列1类:
class array1{
public:
int arr[8];
bool operator < (const array1 & in) const{
for(int i = 0; i < 8; i++){
if(arr[i] < in.arr[i])
return true;
}
return false;
}
bool is_sorted() const{
for(int i = 0; i < 8; i++){
if(i + 1 != abs(arr[i])) return false;
}
return true;
}
void print(){
for(int i = 0; i < 8; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
};
线截图visited[v] = true
应该visited[v]
等于1,但在立即下一行,它被打印并且值被打印为0.
并且当您使用调试器来遍历您的代码时,一次一行地检查所有变量的值,其中观察到的逻辑确切地与预期结果有什么不同? –
我建议你阅读Eric Lippert的[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/),并学习如何使用调试器。 –
索引i总是指向一个数字,而j总是指向一个空的空间。所以,如果一个数字想要转到j所指向的空白区域,那么它必须与j-1中的数字或j + 1中的数字跳舞。第一个条件j -1> = 0检查j-1是否超出范围,然后如果arr [i]和arr [j-1]的乘积值小于零,则至少有一个是女性和其他因为数字arr [i]不能定位arr [i-1]或arr [i + 1],所以需要检查,最后我检查arr [j-1]和arr [i]是素数 –