这是我作业的一部分,即在 ax,y 图中找到两点之间的最短路径(图的大小为 640*340。)。路径应该只通过 (X,Y) 值是整数的点。我是 C++ 新手,但是老师告诉我们我们已经用 C++ 编写了代码。我的代码如下:
#include <iostream>
#include <unordered_map>
#include <utility>
#include <array>
#include <cmath>
using namespace std;
class nodePoint {
public:
int x;
int y; // the x, y cordinates of each point
nodePoint * prevPostion; // a pointer towards the previous point in the path leading to it.
int distance; // how many "points" away from the starting point.
};
void findshortest (nodePoint start,nodePoint end){
for (int i=-1; i<2; i++) {
for (int j=-1; j<2; j++) {
nodePoint *nextNode=new nodePoint();
nextNode->x=start.x+i;
nextNode->y=start.y+i;// iterate all the neighboring points of the point.
if (nextNode->x <= 640 && nextNode->y <=360 && nextNode->x >=0 &&nextNode->y>=0 )// check to see if the point is out of the bound
{
if (nextNode->x==end.x && nextNode->y==end.y) // the point is the ending points.
{
if (end.distance>start.distance+1) {
end.prevPostion=&start;
end.distance=start.distance+1;
}
}else{
findshortest(*nextNode, end);
}
}
}
}
}
int main()
{
nodePoint *one=new nodePoint();// "one" is the starting point
one->x=1;
one->y=2; //just for testing.
one->distance=0;
nodePoint *two=new nodePoint();// "two" is the end point
two->x=3;
two->y=4; // just for testing.
two->distance=pow(two->distance, 10);//set the initial distance value of the end point. It should be a very big number, so that it will be replaced later.
findshortest(*one, *two); //look for the shortest path using the function we just defined.
nodePoint *printer=new nodePoint(); // set a node to iterate over the shortest path through the previous node.
printer=two;
while (two->prevPostion!=NULL) {
printf("%d,%d",printer->x,printer->y); // print out the (x,y) value of each of the point on the path.
printer=two->prevPostion;
}
return 0;
}