is there a good algorithm for checking whether there are 5 same elements in a row or a column or diagonally given a square matrix, say 6×6?
there is ofcourse the naive algorithm of iterating through every spot and then for each point in the matrix, iterate through that row, col and then the diagonal. I am wondering if there is a better way of doing it.
You can check whether there are k same elements in a matrix of integers in a single pass.
Suppose that n is the size of the matrix and m is the largest element. We have n column, n row and 1 diagonal.
Foreach column, row or diagonal we have at most n distinct element.
Now we can create a histogram containing (n + n + 1) * (2 * m + 1) element. Representing
the rows, columns and the diagonal each of them containing at most n distinct element.
Now the tricky part is how to update this histogram ?
Consider this function in pseudo-code:
Now all you have to do is to iterate throw the histogram and check whether there is an element > k