标签:def and for grid tput orm count ges ber
1 """ 2 Given a 2d grid map of ‘1‘s (land) and ‘0‘s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 3 Example 1: 4 Input: 5 11110 6 11010 7 11000 8 00000 9 Output: 1 10 Example 2: 11 Input: 12 11000 13 11000 14 00100 15 00011 16 Output: 3 17 """ 18 """ 19 本题与1162,542 类似 20 有BFS,和DFS两种做法, 21 解法一:BFS 22 我个人更习惯BFS的做法 23 """ 24 class Solution1: 25 def numIslands(self, grid): 26 if not grid or not grid[0]: 27 return 0 28 queue = [] 29 res = 0 30 m = len(grid) 31 n = len(grid[0]) 32 for x in range(m): 33 for y in range(n): 34 if grid[x][y] == ‘1‘: 35 res += 1 36 grid[x][y] == ‘0‘ #!!!找到为1的,将其变为0,并从四个方向遍历,把整个岛变为0 37 queue.append((x, y)) 38 while queue: 39 a, b = queue.pop() 40 for i, j in [(a+1, b), (a-1, b), (a, b-1), (a, b+1)]: 41 if 0 <= i < m and 0 <= j < n and grid[i][j] == ‘1‘: 42 grid[i][j] = ‘0‘ 43 queue.append((i, j)) 44 return res 45 46 """ 47 我们对每个有“1"的位置进行dfs,把和它四联通的位置全部变成“0”,这样就能把一个点推广到一个岛。 48 所以,我们总的进行了dfs的次数,就是总过有多少个岛的数目。 49 注意理解dfs函数的意义:已知当前是1,把它周围相邻的所有1全部转成0. 50 """ 51 class Solution2: 52 def numIslands(self, grid): 53 if not grid or not grid[0]: 54 return 0 55 queue = [] 56 res = 0 57 m = len(grid) 58 n = len(grid[0]) 59 for x in range(m): 60 for y in range(n): 61 if grid[x][y] == ‘1‘: 62 self.dfs(grid, x, y) 63 res += 1 64 return res 65 66 def dfs(self, grid, a, b): 67 grid[a][b] = 0 68 for i, j in [(a + 1, b), (a - 1, b), (a, b - 1), (a, b + 1)]: 69 if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == ‘1‘: 70 self.dfs(grid, i, j)
标签:def and for grid tput orm count ges ber
原文地址:https://www.cnblogs.com/yawenw/p/12314992.html