I have a strange problem. I have the following piece of code in C++:
int grid[h][w]; int dp[h][w]; int p[h][w];
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
cin >> grid[y][x];
// base case
for(int y = 0; y < h; y++) dp[y][0] = grid[y][0];
// fill rest
for(int x = 1; x < w; x++)
{
for(int y = 0; y < h; y++)
{
dp[y][x] = min(dp[y][x-1], min(dp[(y-1)%h][x-1], dp[(y+1)%h][x-1])) + grid[y][x];
}
}
cout << "dp: " << endl;
for(int y = 0; y < h; y++) cout << dp[y][w-1] << endl;
As you can see, in the last lines I’m printing the last column of the dp array (in which I’m interested). When I add the following statement, just below // base case:
p[0][0] = 3;
My dp array changes and I don’t know why. I’ve only added that statement and I wonder why the dp array is changing and how I can prevent this.
Could someone explain this to me why this happens?
Thanks!
Your code has undefined behaviour. Consider what happens inside the following loop when
y = 0:Did you mean to say
(y+h-1)%hinstead of(y-1)%h?