我使用广度优先搜索(如此队列)从X1.X2.X3.X4.X5(例如,0.0.0.3.0)的位置到0.0.0.0.0。我能够达到目标。我只需要打印最短的路径。我认为跟踪指向父级的指针将起作用。但是,到目前为止,我在每个代码中更新所述指针时遇到了很多麻烦。
class Position {
private:
static int move;
vector<int> pos;
Position* start;
Position* next;
static int ctorCounter;
static int dtorCounter;
public:
Position();
Position(vector<int>);
~Position();
void setNext(Position*);
int getCounter();
Position* afterMove(int);
bool isDone();
bool operator==(Position&);
friend ostream& operator<<(ostream&, const Position&);
};
void Position::setNext(Position* P) {
Position* cursor = start;
if(ctorCounter == 1) {
start = P;
}
else {
cursor->next = P;
cursor = cursor->next;
}
}
while(!posQueue.empty()) {
Position* before = posQueue.front();
//cout << *before << endl;
if(before->isDone()) {
break;
}
for(int k = 1; k <= 5; k++) {
Position* after = before->afterMove(k);
if(after != nullptr) {
P.setNext(after);
posQueue.push(after);
}
}
posQueue.pop();
}
答案 0 :(得分:1)
BFS无法帮助你找到从点到点的最短路径,有许多贪心算法,如Kruskal's Minimum Spanning Tree和Dijkstra's Shortest Path Algorithm,以找到最短路径。