代码随想录算法训练营第四十四天| 99. 岛屿数量 深搜、 100.岛屿的最大面积

写代码的第四十四天
图论。。。。。没有视频的日子,纯纯硬背
bfs没懂。。。
只写了dfs。。。。

99. 岛屿数量 深搜

思路

怎么说呢这个题,就是看着代码硬理解。。没视频我感觉我再硬背代码,救命。。。
深搜代码dfs1

direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]  # 四个方向:上、右、下、左
def dfs(grid, visited, x, y):
    """
    对一块陆地进行深度优先遍历并标记
    """
    for i, j in direction:
        next_x = x + i
        next_y = y + j
        # 下标越界,跳过
        if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
            continue
        # 未访问的陆地,标记并调用深度优先搜索
        if not visited[next_x][next_y] and grid[next_x][next_y] == 1:
            visited[next_x][next_y] = True
            dfs(grid, visited, next_x, next_y)

if __name__ == '__main__':  
    # 版本一
    n, m = map(int, input().split())
    # 邻接矩阵
    grid = []
    for i in range(n):
        grid.append(list(map(int, input().split())))    
    # 访问表
    visited = [[False] * m for _ in range(n)]   
    res = 0
    for i in range(n):
        for j in range(m):
            # 判断:如果当前节点是陆地,res+1并标记访问该节点,使用深度搜索标记相邻陆地。
            if grid[i][j] == 1 and not visited[i][j]:
                res += 1
                visited[i][j] = True
                dfs(grid, visited, i, j)    
    print(res)

深搜代码dfs2

def dfs(grid, visited, x, y):
    if visited[x][y] or grid[x][y] == 0:
        return
    visited[x][y] = True
    for i, j in direction:
        next_x = x + i
        next_y = y + j
        if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
            continue
        dfs(grid, visited, next_x, next_y)

100.岛屿的最大面积

思路

这个题和上面的题差不多,只不过在回溯dfs的时候记录一下周围哪里被改成true了,做好记录。
dfs代码

direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]  # 四个方向:上、右、下、左
count = 0

def dfs(grid, visited, x, y):
    global count
    for i, j in direction:
        next_x = x + i
        next_y = y + j
        # 下标越界,跳过
        if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
            continue
        # 未访问的陆地,标记并调用深度优先搜索
        if not visited[next_x][next_y] and grid[next_x][next_y] == 1:
            visited[next_x][next_y] = True
            count += 1
            dfs(grid, visited, next_x, next_y)

if __name__ == '__main__':
    n, m = map(int, input().split())
    grid = []
    for i in range(n):
        grid.append(list(map(int, input().split())))
        
    visited = [[False] * m for _ in range(n)]
    res = 0
    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1 and not visited[i][j]:
                count = 1
                visited[i][j] = True
                dfs(grid, visited, i, j)
                res = max(res, count)
                
    print(res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值