River Sizes

Tiffany ·2024년 3월 13일
0

AlgoExpert

목록 보기
19/20

def riverSizes(matrix):
    listOfRiver = []
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            lengthOfRiver = dfs(i, j, matrix)
            if lengthOfRiver:  # if 0, then bypass #that's why return 0 in the below function
                listOfRiver.append(lengthOfRiver)

    return listOfRiver


def dfs(x, y, matrix):
    row = len(matrix)
    col = len(matrix[0])

    # boundary check
    if x < 0 or y < 0 or x >= row or y >= col:
        return 0
    if matrix[x][y] == 0:
        return 0

    ttlRiverSize = 1
    matrix[x][y] = 0  # mark as 0

    dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
    for i in range(0, len(dirs)):
        newX = x + dirs[i][0]
        newY = y + dirs[i][1]
        ttlRiverSize += dfs(newX, newY, matrix)
    return ttlRiverSize
profile
Love what you do and don't quit.

0개의 댓글