```
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
q=[]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
q.append((i,j))
res = 0
directions = [[0,1],[0,-1],[1,0],[-1,0]]
while q:
r, c = q.pop(0)
#upper
for direct in directions:
newr = r+direct[0]
newc = c+direct[1]
if newr < 0 or newc < 0 or newr >=m or newc >= n:
res+=1
elif grid[newr][newc] == 0:
res+=1
return res
```