Skip to content

solves number of enclaves (#1020) in python #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions python/number_of_enclaves.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# https://leetcode.com/problems/number-of-enclaves/description/
# T: O(m*n)
# S: O(m*n)

from typing import List

class Solution:
def dfs(self, x: int, y: int, m: int, n: int, grid: List[List[int]], visit: List[List[bool]]):
if x < 0 or x >= m or y < 0 or y >= n or visit[x][y] or grid[x][y] == 0:
return
visit[x][y] = True
self.dfs(x+1, y, m, n, grid, visit)
self.dfs(x-1, y, m, n, grid, visit)
self.dfs(x, y+1, m, n, grid, visit)
self.dfs(x, y-1, m, n, grid, visit)

def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
visit = [[False for _ in range(n)] for _ in range(m)]

# Traverse the first and last columns.
for i in range(m):
if grid[i][0] == 1 and not visit[i][0]:
self.dfs(i, 0, m, n, grid, visit)
if grid[i][n-1] == 1 and not visit[i][n-1]:
self.dfs(i, n-1, m, n, grid, visit)

# Traverse the first and last rows.
for j in range(n):
if grid[0][j] == 1 and not visit[0][j]:
self.dfs(0, j, m, n, grid, visit)
if grid[m-1][j] == 1 and not visit[m-1][j]:
self.dfs(m-1, j, m, n, grid, visit)

# Count the number of unvisited land cells.
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and not visit[i][j]:
count += 1

return count