I have a 2d array which has either a 0 or 1 contained within, i want to write a program that checks to see if there a two 1 lying on the same row or column. It should be a O(n**2) algorithm. I have written in python a for loop which loops through the array but i don't get how i can check to see if two 1 are contained in either the row or column, maybe someone can give me some tips. Thanks in advance
a = [[1,0,1,1],[0,1,0,1]]
for i in range(len(a)) :
for j in range(len(a[i])) :
print(a[i][j], end=" ")
print()
def two_adjacent_ones(arr):
for i in range(len(arr) - 1):
for j in range(len(arr[i]) - 1):
if (arr[i][j] == 1 and arr[i][j + 1] == 1) or (arr[i][j] == 1 and arr[i + 1][j] == 1):
return True
last_row = arr[len(arr) - 1]
for i in range(len(last_row) - 1):
if last_row[i] == last_row[i + 1] and last_row[i] == 1:
return True
last_column = [arr[i][-1] for i in range(len(arr) - 1)]
for i in range(len(last_column) - 1):
if last_column[i] == last_column[i + 1] and last_column[i] == 1:
return True
return False
b = [[1, 0, 1, 0], [0, 1, 1, 0]]
print(two_adjacent_ones(b))
this is the most iterative and not pythonic solution i came up with right now.