Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f9079e5

Browse files
solves number of enclaves (#1020) in python
1 parent f607b2a commit f9079e5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

python/number_of_enclaves.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# https://leetcode.com/problems/number-of-enclaves/description/
2+
# T: O(m*n)
3+
# S: O(m*n)
4+
5+
from typing import List
6+
7+
class Solution:
8+
def dfs(self, x: int, y: int, m: int, n: int, grid: List[List[int]], visit: List[List[bool]]):
9+
if x < 0 or x >= m or y < 0 or y >= n or visit[x][y] or grid[x][y] == 0:
10+
return
11+
visit[x][y] = True
12+
self.dfs(x+1, y, m, n, grid, visit)
13+
self.dfs(x-1, y, m, n, grid, visit)
14+
self.dfs(x, y+1, m, n, grid, visit)
15+
self.dfs(x, y-1, m, n, grid, visit)
16+
17+
def numEnclaves(self, grid: List[List[int]]) -> int:
18+
m, n = len(grid), len(grid[0])
19+
visit = [[False for _ in range(n)] for _ in range(m)]
20+
21+
# Traverse the first and last columns.
22+
for i in range(m):
23+
if grid[i][0] == 1 and not visit[i][0]:
24+
self.dfs(i, 0, m, n, grid, visit)
25+
if grid[i][n-1] == 1 and not visit[i][n-1]:
26+
self.dfs(i, n-1, m, n, grid, visit)
27+
28+
# Traverse the first and last rows.
29+
for j in range(n):
30+
if grid[0][j] == 1 and not visit[0][j]:
31+
self.dfs(0, j, m, n, grid, visit)
32+
if grid[m-1][j] == 1 and not visit[m-1][j]:
33+
self.dfs(m-1, j, m, n, grid, visit)
34+
35+
# Count the number of unvisited land cells.
36+
count = 0
37+
for i in range(m):
38+
for j in range(n):
39+
if grid[i][j] == 1 and not visit[i][j]:
40+
count += 1
41+
42+
return count

0 commit comments

Comments
 (0)