python的,就拿了30,感觉逻辑没错,大佬求助
查看原帖
python的,就拿了30,感觉逻辑没错,大佬求助
1231862
lzysxfcs楼主2024/4/14 23:01
def dfs(grid,row,col):
    directions = [(0,1),(0,-1),(-1,0),(1,0)]
    grid[row][col] = '0'
    #更新位置
    for d in directions:
        new_row = row + d[0]
        new_col = col + d[1]
        #是否在矩阵内,是否是细胞
        if 0<= new_row <len(grid) and 0<= new_col <len(grid[0]) and grid[new_row][new_col] != '0':
            dfs(grid,new_row,new_col)

def xibao(grid):
    count = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            #如果是细胞
            if grid[i][j] != '0':
                dfs(grid,i,j)
                count +=1
    return count
n,m = map(int,input().split())
grid = [list(input()) for _ in range(n)]
print(xibao(grid))

2024/4/14 23:01
加载中...