问题描述
LeetCode代码
class Solution:
def countSubIslands(self, grid1, grid2):
SubIslands_num = 0
to_check = set()
flag = 0
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
for i in range(len(grid2)):
for j in range(len(grid2[0])):
if grid2[i][j] == 1:
grid2[i][j] = 0
to_check.add((i, j))
if grid1[i][j] == 0:
flag = 1
while to_check:
ix, iy = to_check.pop()
for dx, dy in directions:
if 0 <= ix + dx < len(grid2) and 0 <= iy + dy < len(grid2[0]):
if grid2[ix + dx][iy + dy] == 1:
grid2[ix + dx][iy + dy] = 0
to_check.add((ix + dx, iy + dy))
if grid1[ix + dx][iy + dy] == 0:
flag = 1
if flag:
flag = 0
else:
SubIslands_num += 1
return SubIslands_num
grid1 = [[1, 1, 1, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 1, 0, 1, 1]]
grid2 = [[1, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 1, 0, 0, 0], [1, 0, 1, 1, 0], [0, 1, 0, 1, 0]]
print(Solution().countSubIslands(grid1, grid2))
grid1 = [[1, 0, 1, 0, 1], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1]]
grid2 = [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]
print(Solution().countSubIslands(grid1, grid2))
结果,可以看出,速度还有待优化
pycharm代码
class Solution:
def countSubIslands(self, grid1, grid2):
SubIslands_num = 0
to_check = set()
flag = 0
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
for i in range(len(grid2)):
for j in range(len(grid2[0])):
if grid2[i][j] == 1:
grid2[i][j] = 0
to_check.add((i, j))
if grid1[i][j] == 0:
flag = 1
while to_check:
ix, iy = to_check.pop()
for dx, dy in directions:
if 0 <= ix + dx < len(grid2) and 0 <= iy + dy < len(grid2[0]):
if grid2[ix + dx][iy + dy] == 1:
grid2[ix + dx][iy + dy] = 0
to_check.add((ix + dx, iy + dy))
if grid1[ix + dx][iy + dy] == 0:
flag = 1
if flag:
flag = 0
else:
SubIslands_num += 1
return SubIslands_num
grid1 = [[1, 1, 1, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 1, 0, 1, 1]]
grid2 = [[1, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 1, 0, 0, 0], [1, 0, 1, 1, 0], [0, 1, 0, 1, 0]]
print(Solution().countSubIslands(grid1, grid2))
grid1 = [[1, 0, 1, 0, 1], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1]]
grid2 = [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]
print(Solution().countSubIslands(grid1, grid2))