动态规划-----捡苹果的案例

一个(N,M)大小的方格,交点处会随机出现苹果,规则是从左上顶点到右下顶点走,且只能向下向右走,求最多能捡多少个苹果

动态规划的问题:设在点(n,m)处有一个苹果,则对于点(n,m)处最多的苹果数 S(n,m)=max{S(i,j)+1,1};

所以,代码如下:

class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public static int Apple(int[,] arr, out List<Point> path)
        {
            int result = 0;
            path = new List<Point>();

            int[,] max = new int[arr.GetLength(0), arr.GetLength(1)];

            for (int i = 0; i < arr.GetLength(0); i++)
            {
                for (int j = 0; j < arr.GetLength(1); j++)
                {
                    max[i, j] = 0;
                    for (int i_temp = 0; i_temp <= i; i_temp++)
                    {
                        for (int j_temp = 0; j_temp <= j; j_temp++)
                        {
                            if ((i > i_temp || j > j_temp) && arr[i, j] == 1 && max[i_temp, j_temp] + 1 > max[i, j])
                            {
                                max[i, j] = max[i_temp, j_temp] + 1;
                                path.Add(new Point() { X = i_temp, Y = j_temp });
                            }
                        }

                    }
                    if (result < max[i, j])
                    {
                        result = max[i, j];


                        max[i, j] = 0;
                        path.Clear();

                        for (int i_temp = 0; i_temp <= i; i_temp++)
                        {
                            for (int j_temp = 0; j_temp <= j; j_temp++)
                            {
                                if ((i > i_temp || j > j_temp) && arr[i, j] == 1 && max[i_temp, j_temp] + 1 > max[i, j])
                                {
                                    max[i, j] = max[i_temp, j_temp] + 1;
                                    path.Add(new Point() { X = i_temp, Y = j_temp });
                                }
                            }

                        }
                        path.Add(new Point() { X = i, Y = j });

                    }
                }

            }

            return result;
        }
    }

测试代码:

int[,] arr=new int[10,10];

            arr[1, 2] = 1;
            arr[2, 1] = 1;
            arr[1, 8] = 1;
            arr[8, 2] = 1;
            arr[4, 7] = 1;
            arr[7, 6] = 1;
            arr[3, 2] = 1;
            arr[1, 9] = 1;
            arr[9, 2] = 1;
            arr[9, 4] = 1;

            List<Point> path;

            int result = Point.Apple(arr,out path);

            Console.WriteLine(result);
            Console.Read();

可以见到,不光可以获取到最多的苹果个数,还可以得到最优的路径:-D

原文地址:https://www.cnblogs.com/LouisGuo/p/4646830.html