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 assume all four edges of the grid are all surrounded by water.
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
visited = set()
for i in range(rows):
for j in range (cols):
if grid[i][j] == '1' and (i,j) not in visited:
count+=1
self.bfs(grid, visited, i, j)
return count
def bfs(self, grid: List[List[str]], visited:set, i:int, j:int):
queue = deque([(i, j)])
visited.add((i,j))
while queue:
row, col = queue.popleft()
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for dr, dc in directions:
nr, nc = row + dr, col + dc
if 0 <= nr < len(grid) and 0<= nc <len(grid[0]) and grid[nr][nc] == '1' and (nr, nc) not in visited:
visited.add((nr,nc))
queue.append((nr,nc))
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
def dfs(i, j):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '#'
dfs(i + 1, j) # 아래로
dfs(i - 1, j) # 위로
dfs(i, j + 1) # 오른쪽으로
dfs(i, j - 1) # 왼쪽으로
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i, j)
count += 1
return count

