If you insist on brute-force, then as you said, you need to iterate over all [x,y]
,
which will be the starting points of the rows.
From these you can iterate over k
adjacent elements in all directions.
You can store the directions as vectors in an array.
This would run in O(k n^2)
.
For n x n
matrix and looking for k
elements in row, C-like pseudocode would look like this (note there is no bounds checking, for the sake of simplicity):
// define an array of directions as [x,y] unit vectors
// you only need to check in 4 directions, other 4 are the same, just reversed
int[4][2] dirs = {{1,0}, {1,1}, {0,1}, {-1,1}};
// iterate over all starting positions
for (x = 0; x < n; ++x) {
for (y = 0; y < n; ++y) {
// iterate over all directions
for (d = 0; d < 4; ++d) {
result = 1;
// iterate over elements in row starting at [x,y]
// going in direction dirs[d]
for (i = 0; i < k; ++i) {
// multiply current result by the element,
// which is i places far from the beginning [x,y]
// in the direction pointed by dirs[d]
new_x = x + i * dirs[d][0];
new_y = y + i * dirs[d][1];
// you need to check the bounds, i'm not writing it here
// if new_x or new_y are outside of the matrix
// then continue with next direction
result *= matrix[new_x][new_y];
}
if (result > max) {
max = result;
}
}
}
}
Slightly better, less of a brute-force way would be to
start on the boundary of a matrix, pick a direction and go in this direction to the opposite side of the matrix, keeping the product of the last k
numbers on the way.
While walking, you keep the product, multiplying it by the number you got to and dividing by the number you left k
steps ago.
This way, with some bounds checking of course,
the product is always product of the last k
numbers,
therefore if the current product is more than maximum, just let max = product
.
This runs always in O(n^2)
.