尝试在c++中找到(x,y)坐标系中两点之间的最短路径.误差11db

try to find the shortest path between two points in a (x,y) coordinate system in C++. Got 11db erro

本文关键字:两点 11db 误差 最短路径 坐标系 之间 c++      更新时间:2023-10-16

这是我作业的一部分,是找到x,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;
}

我真的不明白你在这里想做什么,但我知道如果你想得到一个十进制的答案,你应该使用浮点数或双精度数而不是整数。

顺便说一下,最短过去不就是勾股定理吗?

点(Ax, Ay)和(Bx, By)的最短路径应该是√((Bx-Ax)^2 + (By-Ay)^2)