+ 1
largest product in a grid
In the 20×20 grid below ,What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? Here is my code: https://code.sololearn.com/cxreebx153BL/#c The result should be 70600674. but every time i run the program i got a random number as result. i think it's because i accessed a memory location that is out of my array. But i don't know where.
2 odpowiedzi
+ 3
You are right, you access elements out of bounds in the loop for the first two if-statements where you accidentally check the wrong variables in the wrong if condition. So inside the ifs you look ahead 3 elements for the wrong variable.
// below should be i < 17
if (j < 17) {
horizontal = arr[i][j] * arr[i+1][j] * arr[i+2][j] * arr[i+3][j];
. . .
}
// below should be j < 17
if (i < 17){
vertical = arr[i][j] * arr[i][j+1] * arr[i][j+2] * arr[i][j+3];
. . .
}
+ 1
Thanks