파비의 매일매일 공부기록

2023.04.07 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.07 Today's Challenge

fabichoi 2023. 4. 7. 23:45

https://leetcode.com/problems/number-of-enclaves/

 

Number of Enclaves - LeetCode

Can you solve this real interview question? 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. A move consists of walking from one land cell to another adjacent (4-directionally) land

leetcode.com

전형적인 dfs 문제

class Solution:
    def numEnclaves(self, grid: List[List[int]]) -> int:
        def dfs(i, j):
            grid[i][j] = 0
            for x, y in (i-1, j), (i+1, j), (i, j-1), (i, j+1):
                if 0 <= x < m and 0 <= y < n and grid[x][y]:
                    dfs(x, y)

        m, n = len(grid), len(grid[0])

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1 and (i == 0 or j == 0 or i == m -1 or j == n - 1):
                    dfs(i, j)
        
        return sum(sum(row) for row in grid)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.04.09 Today's Challenge  (0) 2023.04.09
2023.04.08 Today's Challenge  (0) 2023.04.08
2023.04.06 Today's Challenge  (0) 2023.04.06
2023.04.05 Today's Challenge  (0) 2023.04.05
2023.04.04 Today's Challenge  (0) 2023.04.04
Comments