I Want to initialize a global 2d array with -1, currently, I'm able to declare a global 2d array and initialize it with -1 in the main function by below approach;
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int dp[10][100];
int knapsack(vector<int>wt,vector<int>val,int w,int n){
if(w==0 || n==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]+knapsack(wt,val,w-wt[n-1],n-1), knapsack(wt,val,w,n-1))
}
else{
return dp[n][w]=knapsack(wt,val,w,n-1);
}
}
int main(){
vector<int>val={60,100,120};
vector<int>wt={10,20,30};
int w=60;
int n=val.size();
for(int i=0;i<10;i++){
for(int j=0;j<100;j++){
dp[i][j]=-1;
}
}
cout<<knapsack(wt,val,w,n);
}
To initialize with -1 outside main function i tried to modify my code as below but it resulted in an error;
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int dp[10][100];
for(int i=0;i<10;i++){
for(int j=0;j<100;j++){
dp[i][j]=-1;
}
}
int knapsack(vector<int>wt,vector<int>val,int w,int n){
if(w==0 || n==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]+knapsack(wt,val,w-wt[n-1],n-1), knapsack(wt,val,w,n-1));
}
else{
return dp[n][w]=knapsack(wt,val,w,n-1);
}
}
int main(){
vector<int>val={60,100,120};
vector<int>wt={10,20,30};
int w=60;
int n=val.size();
cout<<knapsack(wt,val,w,n);
}
How to initialize my 2D array outside the main function, as sometimes we have to write just function and we are not able to modify code inside main. kindly looking for help.