标签:toggle [] -o body info solution its lte ret
题目描述:
给一个01矩阵,求不同的岛屿的个数。
0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
在矩阵:
[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]
中有 3
个岛.
题目分析:
循环2维数组,找到其值为1的元素,count++,
然后递归改变其上下左右为1的元素值为0,
循环继续。
源码:
class Solution: # @param {boolean[][]} grid a boolean 2D matrix # @return {int} an integer def numIslands(self, grid): # Write your code here if grid is None: return None if grid == []: return 0 # 当数组不为空时,计算行数和列数 self.n = len(grid) self.m = len(grid[0]) x = 0 for i in range(self.n): for j in range(self.m): if grid[i][j] == 1: x += 1 grid = self.change(grid,i,j) return x def change(self,grid,i,j): grid[i][j] = 0 if i > 0 and grid[i-1][j] == 1: # 置当前点上边的点为0 grid = self.change(grid,i-1,j) if i < self.n-1 and grid[i+1][j] == 1: # 置当前点下边的点为0 grid = self.change(grid,i+1,j) if j < self.m-1 and grid[i][j+1] == 1: # 置当前点右方的点为0 grid = self.change(grid,i,j+1) if j > 0 and grid[i][j-1] == 1: # 置当前点左方的点为0 grid = self.change(grid,i,j-1) return grid
LintCode Python 简单级题目 433.岛屿的个数
标签:toggle [] -o body info solution its lte ret
原文地址:http://www.cnblogs.com/bozhou/p/6956382.html