#include <iostream>
using namespace std;
#include <list>
//A queue for the working set
//x,y co-ords of the square, path length so far
struct square {
int x;
int y;
int path_length;
};
list<square> workingset;
//A 2D array of ints to represent the board (duplicates list)
int board[10][10];
void generatelegalmove(square node, int x_offset, int y_offset);
void printboard();
void main()
{
//Initialises the board
int i, j;
for (i=0; i<10; i++)
{
for (j=0; j<10; j++)
{
board[i][j] = 0;
}
}
//The goal position - a number we will never reach
board[8][8] = 1337;
bool goal_found = false;
//Sets up initial position
square temp = {3, 7, 1};
//Put initial position in working set and duplicates list
workingset.push_back(temp);
board[3][7] = 1;
//Loop (until a goal is found)
while(!goal_found)
{
//Get the head node from the working set
square nodetocheck = workingset.front();
//Exit if the goal has been found
if(board[nodetocheck.x][nodetocheck.y] == 1337)
{
goal_found = true;
break;
}
//Generate the legal moves
generatelegalmove(nodetocheck, -1, 0); //One square to the left
generatelegalmove(nodetocheck, 0, -1); //One square up
generatelegalmove(nodetocheck, 1, 0); //One square to the right
generatelegalmove(nodetocheck, 0, 1); //One square down
if(!workingset.empty())
{
//workingset.pop_front();
}
//End Loop
}
//Print the Board
printboard();
while(true);
//Trace back and print Trace back (once implemented)
//Print other info
}
void generatelegalmove(square node, int x_offset, int y_offset)
{
node.x = node.x + x_offset;
node.y = node.y + y_offset;
node.path_length = node.path_length+1;
//Is this square on the board
if((node.x >= 0) &&
(node.x < 10) &&
(node.y >= 0) &&
(node.y < 10) &&
//Is this square empty
(board[node.x][node.y] == 0))
{
workingset.push_back(node);
board[node.x][node.y] = node.path_length;
//Add to working set
//Add to duplicates list
}
//(If a graphical animation is added, do it here, by printing the new board after each one, then sleeping for a few seconds)
}
我得到运行时错误'list iterator not dereferencable'。
我假设这与在while循环中调用workingset.pop_front()
有关,但我不确定应该采取什么措施来解决这个问题。
每个循环,我想从列表的前面获取节点,稍微使用它,然后从列表中删除该节点。
这是generatelegalmove()的代码 - 正如你所看到的,如果新的方块在板上(即在数组的两个维度中在0-9范围内,并且方块为空),它将添加这个新节点到工作集和board [] [](实际上是一个有效的重复列表)
答案 0 :(得分:2)
鉴于您提供的样本,我可以看到一件事是错的。在每次循环迭代结束时,弹出前节点。但是,如果goal_found
为真,则只退出循环,表示行:
square nodetocheck = workingset.front();
...很可能访问一个空的工作集。显然你在这里调用了可能添加节点的其他函数,但是如果没有节点,这可能是个问题。
编辑:我认为您的代码没有添加其他节点,因为您使用的是按位和&
运算符而不是逻辑和&&
运算符,导致您的工作集不会获取节点。