Untitled

mail@pastecode.io avatar
unknown
python
a month ago
833 B
5
Indexable
Never
def is_valid_diagonal(x, y, dx, dy):
    cx, cy, i = x, y, 0
    while 0 <= cx + dx < len(matrix) and 0 <= cy + dy < len(matrix[0]):
        cx += dx
        cy += dy

        if i % 2 == 0 and matrix[cx][cy] != 2:
            return False
        elif i % 2 == 1 and matrix[cx][cy] != 0:
            return False

        i += 1

    return True


q = []
dirs = [(1, 1), (-1, -1), (-1, 1), (1, -1)]
diagonals = 0

# get all initial positions of 1
for row in range(len(matrix)):
    for col in range(len(matrix[0])):
        if matrix[row][col] == 1:
            q.append((row, col))

# for each 1 in the matrix
while q:
    x, y = q.pop()

    # get all diagonals at 1 starting positions
    for dx, dy in dirs:
        # count valid diagonals
        if is_valid_diagonal(x, y, dx, dy):
            diagonals += 1

return diagonals
Leave a Comment