目的是输入一段曲线的首尾点,然后利用垂距法得到特征点,以此重新产生两端曲线进行递归,请问下面代码哪里出错了呢
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
namespace test1
{
public class DG
{
List<Point> PList;
public List<Point> keep = new List<Point>();
public int index = 0;
ArrayList d = new ArrayList();
ArrayList dtemp = new ArrayList();
double D = 10.0;
public DG()
{ }
public DG(List<Point> List)
{
PList = List;
}
public void getID(int bid,int eid)
{
Vector temp = new Vector();
for (int i = 0; i < eid - bid + 1; i++)
{
Vector iTOb = new Vector(PList[i],PList[bid]);
Vector iTOe = new Vector(PList[i],PList[eid]);
Vector bTOe = new Vector(PList[bid], PList[eid]);
double length = temp.Length(bTOe);
double cross = Math.Abs(temp.VectorX(iTOb, iTOe)) / 2.0;
double t = cross / length;
d.Add(t);
dtemp.Add(t);
}
if (eid <= bid + 1)
{
return;
}
dtemp.Sort();
dtemp.Reverse();
int maxindex = d.IndexOf(dtemp[0]);
if (((double)dtemp[0]) > D)
{
keep.Add(PList[maxindex]);
d.Clear();
dtemp.Clear();
getID(bid, maxindex);
getID(maxindex, eid);
index++;
}
else return;
}
}
}
我看见你的程序看起来没有明显错误,但是有一些可以改进的地方。
我发现你使用了ArrayList来存储d和dtemp,这是不必要的,因为List可以做到同样的事情。
在getID方法中,你使用了一个循环来遍历eid-bid+1个点,这样会导致重复计算,影响程序的效率。可以改进为用一个变量i来遍历这些点。
在if (eid <= bid + 1)语句块中,你返回了,但是你没有清空d和dtemp这两个数组,这会导致累加。
如果你不能找到问题的根源,可以使用调试器来跟踪程序的运行过程,检查变量和数组的值是否正确。
你具体的错误是什么呢,光看代码没看出来,或者你可以参考下别人怎么实现的,对比下你的代码哪里有出路,定位下问题所在。c#实现道格拉斯算法,可以参考以下资料:
https://www.likecs.com/show-203452007.html
改了下,这样不会无限递归了,谢谢各位
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
namespace test1
{
public class DG
{
List<Point> PList;
public List<int> keep = new List<int>();
public int index = 0;
ArrayList d = new ArrayList();
ArrayList dtemp = new ArrayList();
double D = 10.0;
public DG()
{ }
public DG(List<Point> List)
{
PList = List;
}
public void getID(int bid,int eid)
{
Vector temp = new Vector();
for (int i = bid + 1; i < eid; i++)
{
Vector iTOb = new Vector(PList[i],PList[bid]);
Vector iTOe = new Vector(PList[i],PList[eid]);
Vector bTOe = new Vector(PList[bid], PList[eid]);
double length = temp.Length(bTOe);
double cross = Math.Abs(temp.VectorX(iTOb, iTOe)) / 2.0;
double t = cross / length;
d.Add(t);
dtemp.Add(t);
}
if (eid <= bid + 1)
{
d.Clear();
dtemp.Clear();
return;
}
dtemp.Sort();
dtemp.Reverse();
int maxindex = d.IndexOf(dtemp[0]) + bid + 1;
if (((double)dtemp[0]) > D)
{
keep.Add(maxindex);
index++;
d.Clear();
dtemp.Clear();
getID(bid, maxindex);
getID(maxindex, eid);
}
else
{
d.Clear();
dtemp.Clear();
return;
}
}
}
}