我有这个Python代码,用于计算二进制矩阵中的岛数(分组为1)。我如何修改它以考虑顶部和底部的包裹?
class Solution(object):
rowLen = None
colLen = None
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
self.rowLen = len(grid)
if self.rowLen == 0:
return 0;
self.colLen = len(grid[0])
count = 0;
for row in range(self.rowLen):
for col in range(self.colLen):
if grid[row][col] == '1':
count += 1
self.search(grid, row, col)
return count
def search(self, grid, row, col):
if (row >= 0 and col >= 0 and row < self.rowLen and col < self.colLen and grid[row][col] == '1'):
grid[row][col] = 0;
self.search(grid, row - 1, col)
self.search(grid, row + 1, col)
self.search(grid, row, col - 1)
self.search(grid, row, col + 1)
这当前返回的计数为2,但是应该返回1,因为右下岛应该在左下角用数字包裹后计算为较大岛屿的一部分。
11110
11010
11000
10001
答案 0 :(得分:0)
这不明显吗?你的搜索功能只需要环绕而不是在碰到边缘时停止。
def search(self, grid, row, col):
if row < 0:
row += self.rowLen
elif row >= self.rowlen:
row -= self.rowlen
if col < 0:
col += self.colLen
elif col >= self.colLen:
col -= self.colLen
if grid[row][col] == '1':
grid[row][col] = 0;
self.search(grid, row - 1, col)
self.search(grid, row + 1, col)
self.search(grid, row, col - 1)
self.search(grid, row, col + 1)
这可以在模运算方面更简单地表达:
def search(self, grid, row, col):
row %= self.rowlen
col %= self.colLen
if grid[row][col] == '1':
grid[row][col] = 0;
self.search(grid, row - 1, col)
self.search(grid, row + 1, col)
self.search(grid, row, col - 1)
self.search(grid, row, col + 1)