In a 2D grid of 0
s and 1
s, we change at most one 0
to a 1
.
After, what is the size of the largest island? (An island is a 4-directionally connected group of 1
s).
Example 1:
Input: [[1, 0], [0, 1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: [[1, 1], [1, 0]] Output: 4 Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 1.
Example 3:
Input: [[1, 1], [1, 1]] Output: 4 Explanation: Can't change any 0 to 1, only one island with area = 1.
Notes:
1 <= grid.length = grid[0].length <= 50
.0 <= grid[i][j] <= 1
.
BFS跑一遍,记录每个group的ID
class Solution(object):
def largestIsland(self, a):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not a or not a[0]: return 0
marked = [[False for _ in range(len(a[0]))] for _ in range(len(a[0]))]
dirs=[(-1,0),(1,0),(0,1),(0,-1)]
step = 2
d={}
for i in range(len(a)):
for j in range(len(a[0])):
if not marked[i][j] and a[i][j]==1:
marked[i][j]=True
q=[(i,j)]
cnt=0
while q:
ii,jj=q.pop()
a[ii][jj] = step
cnt+=1
for di,dj in dirs:
iii,jjj=ii+di,jj+dj
if 0<=iii<len(a) and 0<=jjj<len(a[0]) and not marked[iii][jjj] and a[iii][jjj]==1:
marked[iii][jjj] = True
q.append((iii,jjj))
d[step]=cnt
step+=1
res=max(d.values()) if d else 0
for i in range(len(a)):
for j in range(len(a[0])):
if a[i][j]==0:
s=set()
for di,dj in dirs:
ii,jj=i+di,j+dj
if 0<=ii<len(a) and 0<=jj<len(a[0]) and a[ii][jj]!=0:
s.add(a[ii][jj])
tmp=0
for k in s: tmp+=d[k]
res=max(res,tmp+1)
return res
s=Solution()
print(s.largestIsland([[1, 0], [0, 1]]))
print(s.largestIsland([[1, 1], [1, 0]]))
print(s.largestIsland([[1, 1], [1, 1]]))
print(s.largestIsland([[0 ,0], [0 ,0]]))