Day 40 of LeetCode

Day 40 of LeetCode

ยท

2 min read

Documenting LeetCode solving.

Q112

695. Max Area of Island

Medium. Graph

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        ROWS, COLS = len(grid), len(grid[0])
        visit = set()

        # return the area
        def dfs(r, c):
            if (r < 0 or r == ROWS or c < 0 or c == COLS or
                grid[r][c] == 0 or (r, c) in visit):
                return 0

            visit.add((r, c))
            # current area + 4 directions
            return (1 + dfs(r + 1, c)
                      + dfs(r - 1, c)
                      + dfs(r, c + 1)
                      + dfs(r, c - 1))

        res = 0
        for r in range(ROWS):
            for c in range(COLS):
                res = max(res, dfs(r, c))

        return res

Q113

130. Surrounded Regions

Medium. Graph

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        ROWS, COLS = len(board), len(board[0])

        # capture boarder Os
        def dfs(r, c):
            if (r < 0 or r == ROWS or c < 0 or c == COLS or
                board[r][c] != "O"):
                return
            board[r][c] = "T"
            dfs(r + 1, c)
            dfs(r - 1, c)
            dfs(r, c + 1)
            dfs(r, c - 1)

        # 1. capture unsurrounded regions (O -> T)
        for r in range(ROWS):
            for c in range(COLS):
                if (board[r][c] == "O" and
                    (r in [0, ROWS - 1] or c in [0, COLS - 1])):
                    dfs(r, c)
        # 2. capture surrounded regions (O -> X)
        for r in range(ROWS):
            for c in range(COLS):
                if board[r][c] == "O":
                    board[r][c] = "X"
                elif board[r][c] == "T":
                    board[r][c] = "O"
        # 3. uncapture unsurrounded regions (T -> O)
        # for r in range(ROWS):
        #     for c in range(COLS):
        #         if board[r][c] == "T":
        #             board[r][c] = "O"

Did you find this article valuable?

Support ๐Ÿฐ Evelyn's Learning Journey by becoming a sponsor. Any amount is appreciated!

ย