알고리즘/leetcode
1020. Number of Enclaves - python
1.5볼트
2023. 4. 7. 10:11
728x90
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
leetcode는 데일리 문제가 약간 비슷한 유형에서 나오니까 어제와 같은 bfs 문제다 유형뿐 아니라
문제 자체도 그냥 거의 같음 다른 점은 0 과 1이 바뀐 점과 섬의 크기(1의 개수를 세는 점)
어제 사용했던 함수를 그대로 사용한다 그러면 0 과 1만 바꿔주고 섬을 이동할 때마다 전역변수를 1씩 더해준다
만약 True를 리턴하면 끝에 닿지 않는다는 뜻이니까 이때만 섬의 크기를 더해준다
class Solution:
def numEnclaves(self, t: List[List[int]]) -> int:
r=len(t)
l=len(t[0])
def f(x,y):
global w
global s1
s1+=1
t[x][y]=0
for i,j in [[1,0],[-1,0],[0,1],[0,-1]]:
if 0<=x+i<r and 0<=y+j<l:
if t[x+i][y+j]==1:
f(x+i,y+j)
else:
w=True
#return True
s=0
global w
global s1
w=False
for i in range(r):
for j in range(l):
if t[i][j]!=0:
s1=0
w=False
sd=f(i,j)
if not w:
s+=s1
return s