题目
解析:
这道题目的关键就在于,想到只有可能是0,1,2三种答案,想到了这个题目也就非常简单了
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
# check if there is more than one disconnected islands in teh grid
def check(curr_grid):
start_pos = (-1,-1)
for i in range(m):
for j in range(n):
if curr_grid[i][j] == 1:
start_pos = (i,j)
break
if start_pos == (-1,-1):
return True
# find one island first
q = collections.deque()
q.append(start_pos)
island = {start_pos:True}
visited = [[False]*n for _ in range(m)]
visited[start_pos[0]][start_pos[1]] = True
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
while q:
i,j = q.popleft()
for d in dirs:
x = i + d[0]
y = j + d[1]
if 0<=x<m and 0<=y<n and not visited[x][y] and curr_grid[x][y]==1:
q.append((x,y))
visited[x][y] = True
island[(x,y)] = True
# check again if there is any other island
for i in range(m):
for j in range(n):
if curr_grid[i][j] == 1 and (i,j) not in island:
return True
return False
m = len(grid)
n = len(grid[0])
# check if there is only one island
if check(grid):
return 0
# check if remove 1 block can work
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = 0
if check(grid):
return 1
grid[i][j] = 1
# else return 2
return 2
还可以通过检查一次访问到了多少个1的位置和grid一共有多少个1的位置来判断是否只包含一个island
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
# check if there is more than one disconnected islands in teh grid
def check(curr_grid):
start_pos = (-1,-1)
for i in range(m):
for j in range(n):
if curr_grid[i][j] == 1:
start_pos = (i,j)
break
if start_pos == (-1,-1):
return -1
# find one island first
q = collections.deque()
q.append(start_pos)
#island = {start_pos:True}
visited = set()
visited.add(start_pos)
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
while q:
i,j = q.popleft()
for d in dirs:
x = i + d[0]
y = j + d[1]
if 0<=x<m and 0<=y<n and (x,y) not in visited and curr_grid[x][y]==1:
q.append((x,y))
visited.add((x,y))
#island[(x,y)] = True
# check again if there is any other island
# for i in range(m):
# for j in range(n):
# if curr_grid[i][j] == 1 and (i,j) not in island:
# return True
return len(visited)
m = len(grid)
n = len(grid[0])
candidate = []
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
candidate.append((i,j))
# check if there is only one island
tmp = check(grid)
if tmp<len(candidate):
return 0
# check if remove 1 block can work
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = 0
tmp = check(grid)
if tmp<len(candidate)-1:
return 1
grid[i][j] = 1
# else return 2
return 2