尝试在c++中找到(x,y)坐标系中两点之间的最短路径.误差11db
try to find the shortest path between two points in a (x,y) coordinate system in C++. Got 11db erro
这是我作业的一部分,是找到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)
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 找到两点之间的中点
- 如何调整由两点定义的线的大小,使其受C++的最大线长度的约束
- 在C++中计算两点之间的角度,得到了奇怪的结果
- 两点距离的解是什么
- 使用Opencv/c++在Stream中的两点之间绘制aline
- 如何知道数组中两点之间的单元格数
- 计算接触两点的圆心
- 如何有效地计算两点之间的角度
- 如何使用两点和步骤 c++ 之间的元素初始化向量
- 泰勒麦克劳克林级数来估计两点的距离
- 将矩形定义为两点或原点/大小
- 委托和调用父类构造函数:如何做到这两点?
- 查找二维数组中两点之间的距离
- Xcode 11db错误的事情:线程1:EXC_BAD_ACCESS(代码=EXC_I386_GPFLT)
- 尝试在c++中找到(x,y)坐标系中两点之间的最短路径.误差11db
- C++中的两点边值
- 两点交叉操作
- 如何并行嵌套循环,以找到最近的两点在OpenMP
- C++检测两点之间的碰撞,并在发生碰撞时从法线上反弹