如何编写递归函数

时间:2018-12-15 08:36:08

标签: c# .net .net-core

我想写一个像这样的函数:

List<Point>points=FindPoints(allPoints,point);
for(int i=0;i<points.Count;i++){
    List<Point>nextPoints=FindPoints(allPoints,points[i]);
    for(int j=0;j<nextPoints.Count;j++){

........
   }
}

如何递归编写?

1 个答案:

答案 0 :(得分:0)

要递归,您必须将代码的核心放入函子中,然后函子会自我调用,所以:

List<Point> RecursiveFindPoints(List<Point> allPoints, Point point)
{
    List<Point> result = new List<Point>();
    List<Point> points = FindPoints(allPoints,point);
    result.AddRange(points);
    for(int i=0;i<points.Count;i++)
    {
        result.AddRange(RecursiveFindPoints(allPoints,points[i]));
    }
    return result;
}