Skip to content

Commit 79b31de

Browse files
1020 Number of Enclaves.py
1 parent 9c46187 commit 79b31de

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

1020 Number of Enclaves.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
4+
5+
A move consists of walking from one land square 4-directionally to another land
6+
square, or off the boundary of the grid.
7+
8+
Return the number of land squares in the grid for which we cannot walk off the
9+
boundary of the grid in any number of moves.
10+
11+
Example 1:
12+
Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
13+
Output: 3
14+
Explanation:
15+
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed
16+
because its on the boundary.
17+
18+
Example 2:
19+
Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
20+
Output: 0
21+
Explanation:
22+
All 1s are either on the boundary or can reach the boundary.
23+
24+
Note:
25+
1 <= A.length <= 500
26+
1 <= A[i].length <= 500
27+
0 <= A[i][j] <= 1
28+
All rows have the same size.
29+
"""
30+
from typing import List
31+
32+
33+
dirs = ((0, -1), (0, 1), (1, 0), (-1, 0))
34+
35+
36+
class Solution:
37+
def numEnclaves(self, A: List[List[int]]) -> int:
38+
"""
39+
not dfs from any cell, but dfs from the edges
40+
"""
41+
m, n = len(A), len(A[0])
42+
visited = [[False for _ in range(n)] for _ in range(m)]
43+
for i in range(m):
44+
for j in range(n):
45+
if not visited[i][j] and A[i][j] == 1 and (i == 0 or j == 0 or i == m - 1 or j == n - 1):
46+
self.dfs(A, i, j, visited)
47+
48+
ret = 0
49+
for i in range(m):
50+
for j in range(n):
51+
if A[i][j] == 1 and not visited[i][j]:
52+
ret += 1
53+
return ret
54+
55+
def dfs(self, A, i, j, visited):
56+
m, n = len(A), len(A[0])
57+
visited[i][j] = True
58+
for di, dj in dirs:
59+
I = i + di
60+
J = j + dj
61+
if 0 <= I < m and 0 <= J < n and not visited[I][J] and A[I][J] == 1:
62+
self.dfs(A, I, J, visited)
63+
64+
65+
class SolutionError:
66+
def __init__(self):
67+
self.ret = 0
68+
69+
def numEnclaves(self, A: List[List[int]]) -> int:
70+
"""
71+
dfs coloring
72+
"""
73+
m, n = len(A), len(A[0])
74+
visited = [[None for _ in range(n)] for _ in range(m)] # 0 not off, 1 off
75+
for i in range(m):
76+
for j in range(n):
77+
if not visited[i][j] and A[i][j] == 1:
78+
self.dfs(A, i, j, visited)
79+
return self.ret
80+
81+
def dfs(self, A, i, j, visited):
82+
m, n = len(A), len(A[0])
83+
visited[i][j] = 0
84+
for di, dj in dirs:
85+
I = i + di
86+
J = j + dj
87+
if not (0 <= I < m and 0 <= J < n):
88+
visited[i][j] = 1
89+
return True
90+
if visited[I][J] == 1:
91+
visited[i][j] = 1
92+
return True
93+
if visited[I][J] is None and A[I][J] == 1 and self.dfs(A, I, J, visited):
94+
visited[i][j] = 1
95+
return True
96+
97+
self.ret += 1
98+
return False

0 commit comments

Comments
 (0)