leetcode(58)-島嶼數量
阿新 • • 發佈:2020-10-16
給你一個由'1'(陸地)和 '0'(水)組成的的二維網格,請你計算網格中島嶼的數量。
島嶼總是被水包圍,並且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連線形成。
此外,你可以假設該網格的四條邊均被水包圍。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-islands
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
class Solution: def numIslands(self, grid: List[List[str]]) -> int: height = len(grid) width = len(grid[0]) num_of_island = 1 def infect(i,j): four_directions = [(0,-1),(1,0),(-1,0),(0,1)] for (x,y) in four_directions: new_i, new_j = i+x, j+y if 0<=new_i<height and 0<=new_j<width: if grid[new_i][new_j] == "1": grid[new_i][new_j] = num_of_island infect(new_i,new_j) for i in range(height): for j in range(width): if grid[i][j] == "1": num_of_island+=1 grid[i][j] = num_of_island infect(i,j) return num_of_island-1