695. Max Area of Island 1020. Number of Enclaves

695. Max Area of Island

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

DFS:

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        self.visited = [[False] * n for _ in range(m)]
        self.dir = [(0,1),(0,-1),(1,0),(-1,0)]
        result = 0

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1 and not self.visited[i][j]:
                    self.count = 0  #定义在这里,每一次找小岛重置一次
                    self.dfs(grid, i, j, 0)
                    result = max(result, self.count)
        return result

    

    def dfs(self, grid, x, y, count):
        if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or grid[x][y] == 0 or self.visited[x][y]:
            return
        self.visited[x][y] = True
        self.count += 1
        for dir_ in self.dir:
            self.dfs(grid, x + dir_[0], y + dir_[1], 0)

 BFS:

class Solution:
    def __init__(self):
        self.count = 0

    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        # 与200.独立岛屿不同的是:此题grid列表内是int!!!

        # BFS
        if not grid: return 0

        m, n = len(grid), len(grid[0])
        visited = [[False for i in range(n)] for j in range(m)]

        result = 0
        for i in range(m):
            for j in range(n):
                if not visited[i][j] and grid[i][j] == 1:
                    # 每一个新岛屿
                    self.count = 0
                    self.bfs(grid, visited, i, j)
                    result = max(result, self.count)

        return result

    def bfs(self, grid, visited, i, j):
        self.count += 1
        visited[i][j] = True    

        queue = collections.deque([(i, j)])
        while queue:
            x, y = queue.popleft()
            for new_x, new_y in [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]:
                if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and not visited[new_x][new_y] and grid[new_x][new_y] == 1:
                    visited[new_x][new_y] = True
                    self.count += 1
                    queue.append((new_x, new_y))

1020. Number of Enclaves

You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

 

 First, we'll make all the islands next to the border zero.

 

DFS:

class Solution:
    def numEnclaves(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        self.dirs = [(0,1),(0,-1),(1,0),(-1,0)]
        self.visited = [[False] * n for _ in range(m)]        
        count = 0
        
        for i in range(m):
            self.dfs(grid, i, 0)
            self.dfs(grid, i, n - 1)
        for j in range(n):
            self.dfs(grid, 0, j)
            self.dfs(grid, m - 1, j)
        
        for i in range(m):
            for j in range(n):
                if not self.visited[i][j] and grid[i][j] == 1:
                    count += 1
        return count
    
    def dfs(self, grid, x, y):
        if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or self.visited[x][y] or grid[x][y] == 0:
            return
        self.visited[x][y] = True
        grid[x][y] = 0
        for dir_ in self.dirs:
            self.dfs(grid, x + dir_[0], y + dir_[1])

 BFS:

class Solution:
    def __init__(self):
        self.position = [[-1, 0], [0, 1], [1, 0], [0, -1]]	# 四个方向

    # 广度优先遍历,把可以通向边缘部分的 1 全部标记成 true
    def bfs(self, grid: List[List[int]], queue: deque, visited: List[List[bool]]) -> None:
        while queue:
            curPos = queue.popleft()
            for current in self.position:
                row, col = curPos[0] + current[0], curPos[1] + current[1]
                # 索引下标越界
                if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]): continue
                # 当前位置值不是 1 或者已经被访问过了
                if grid[row][col] == 0 or visited[row][col]: continue
                visited[row][col] = True
                queue.append([row, col])


    def numEnclaves(self, grid: List[List[int]]) -> int:
        rowSize, colSize, ans = len(grid), len(grid[0]), 0
        # 标记数组记录每个值为 1 的位置是否可以到达边界,可以为 True,反之为 False
        visited = [[False for _ in range(colSize)] for _ in range(rowSize)]
        queue = deque()		# 队列
        # 搜索左侧边界和右侧边界查找 1 存入队列
        for row in range(rowSize):
            if grid[row][0] == 1:
                visited[row][0] = True
                queue.append([row, 0])
            if grid[row][colSize - 1] == 1:
                visited[row][colSize - 1] = True
                queue.append([row, colSize - 1])
        # 搜索上边界和下边界查找 1 存入队列,但是四个角不用遍历,因为上面已经遍历到了
        for col in range(1, colSize - 1):
            if grid[0][col] == 1:
                visited[0][col] = True
                queue.append([0, col])
            if grid[rowSize - 1][col] == 1:
                visited[rowSize - 1][col] = True
                queue.append([rowSize - 1, col])
        self.bfs(grid, queue, visited)	# 广度优先遍历
        # 找出矩阵中值为 1 但是没有被标记过的位置,记录答案
        for row in range(rowSize):
            for col in range(colSize):
                if grid[row][col] == 1 and not visited[row][col]:
                    ans += 1
        return ans

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值