-3

I am trying to solve a dynamic programming problem using memoization. I need to declare a 2D array as a global variable and initialise all of its element as -1. Then I am going to use this initialised array in a recursive function.

#include<iostream>
using namespace std;
int dp[1002][1002];
//initialize above array as all of its element = -1

int max_value(int val[], int wt[], int n, int W)
{
    if(n==0 || W==0)
    {
        return 0;
    }
    if(dp[n][W] != -1)
    {
        return dp[n][W];
    }
    if(wt[n-1] <= W)
    {
        return dp[n][W] = max(val[n-1] + max_value(val, wt, n-1, W-wt[n-1]), max_value(val, wt, n-1, W));
    }
    else
    {
        return dp[n][W] = max_value(val, wt, n-1, W);

    }
}

Can you tell me how to initialize all the elements of array dp[][] as -1?

Sachin Kumar
  • 366
  • 1
  • 6
  • 20

1 Answers1

1

You can use std::fill

std::fill(&dp[0][0], & dp[1001][1002], -1);
JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
김선달
  • 1,485
  • 9
  • 23