-
[leetcode 75-19] Number of islandsAlgorithm 2023. 1. 31. 23:22
https://leetcode.com/problems/number-of-islands
Number of Islands - LeetCode
Number of Islands - Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may ass
leetcode.com
class Solution(object): def numIslands(self, grid): cnt=0 dx =[1,-1,0,0] dy =[0,0,1,-1] def bfs(x,y,grid): queue = deque() queue.append((x,y)) grid[x][y] = 0 while queue: x,y = queue.popleft() for i in range(4): nx = x+dx[i] ny = y+dy[i] if 0<= nx < len(grid) and 0 <= ny < len(grid[0]): if grid[nx][ny] == "1": grid[nx][ny] = 0 queue.append((nx,ny)) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == "1": bfs(i,j,grid) cnt+=1 return cnt
'Algorithm' 카테고리의 다른 글
[leetcode 75-18] Top K Frequent Elements (0) 2023.01.31 [leetcode 75-17] Coin change (0) 2023.01.30 [leetcode 75-16] Climbing Stairs (0) 2023.01.30 [leetcode 75-15] Reverse Bits (0) 2023.01.30 [leetcode 75-14] Missing Number (0) 2023.01.30