For rows, you can save a counter that indicates how many of the same elements in the row you currently have. To do this, iterate over the line and
- If the current item matches the previous item, increment the counter by one. If the counter is 5, you found 5 items that you wanted.
- If the current item does not match the previous item, set the counter to 1.
The same principle can be applied to columns and diagonals. You will probably want to use an array of counters for columns (one element for each column) and diagonals so that you can iterate over the matrix sequentially.
I made a small example for a smaller size, but you can easily change it:
n = 3 matrix = [[1, 2, 3, 4], [1, 2, 3, 1], [2, 3, 1, 3], [2, 1, 4, 2]] col_counter = [1, 1, 1, 1] for row in range(0, len(matrix)): row_counter = 1 for col in range(0, len(matrix[row])): current_element = matrix[row][col] # check elements in a same row if col > 0: previous_element = matrix[row][col - 1] if current_element == previous_element: row_counter = row_counter + 1 if row_counter == n: print n, 'in a row at:', row, col - n + 1 else: row_counter = 1 # check elements in a same column if row > 0: previous_element = matrix[row - 1][col] if current_element == previous_element: col_counter[col] = col_counter[col] + 1; if col_counter[col] == n: print n, 'in a column at:', row - n + 1, col else: col_counter[col] = 1
I left the diagonals to make the example short and simple, but for diagonals you can use the same principle as in the columns. The previous element would be one of the following (depending on the direction of the diagonal):
matrix[row - 1][col - 1] matrix[row - 1][col + 1]
Please note that in the second case, you will need a little more effort. For example, cross a row in the inner loop from right to left.