コード例 #1
0
        private JumpItem MinimumNumberofJumpsDP(int[] input)
        {
            if (input.Length == 0 || input[0] == 0)
            {
                return(null);
            }

            int[] jumps      = new int[input.Length];
            int[] jumpvalues = new int[input.Length];

            // Find the minimum number of jumps to reach arr[i] from 0 to i -1
            // from arr[0], and assign this value to jumps[i]
            jumps[0]      = 0;
            jumpvalues[0] = -1;

            for (int i = 1; i < input.Length; i++)
            {
                jumps[i] = Int32.MaxValue; //Initialize with max and then we update with actual value
                //Here we need to see whether we can reach i from 0 to i -1...
                //Note i and j should not be equal because there is no reason to start and end at the same place. (No need to jump if the start and end are same)
                for (int j = 0; j < i; j++)
                {
                    //can we reach index i if we jump from j position
                    if (j + input[j] >= i && jumps[j] != Int32.MaxValue)
                    {
                        int steps = jumps[j] + 1;
                        if (steps < jumps[i])
                        {
                            //jumps[i] = min(jumps[i], jumps[j] + 1);
                            jumps[i]      = steps;
                            jumpvalues[i] = j; //index where it came from
                        }
                    }
                }
            }


            //Backtrack with jump values

            StringBuilder sb = new StringBuilder();
            int           k  = input.Length - 1;

            sb.Insert(0, "," + input[k]);

            while (k > 0)
            {
                int lastjumpfromIndex = jumpvalues[k];
                sb.Insert(0, "," + input[lastjumpfromIndex]);
                k = lastjumpfromIndex;
            }

            JumpItem result = new JumpItem();

            result.MinimumJump = jumps[input.Length - 1]; //get the lasat item
            result.Path        = sb.ToString();
            return(result);
        }
コード例 #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            //https://www.youtube.com/watch?v=cETfFsSTGJI

            int[] input = AlgorithmHelper.ConvertCommaSeparetedStringToInt(this.textBox15.Text);

            JumpItem result = MinimumNumberofJumpsDP(input);

            this.textBox12.Text = result.MinimumJump.ToString();
            this.textBox1.Text  = result.Path;
        }