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 assume all four edges of the grid are all surrounded by water.
=> 1(땅), 0(물)을 나타내는 grid가 주어졌을때 섬의 개수를 구하는데 동, 서, 남, 북 으로 인접한 땅은 하나의 섬으로 연결된다.
Solution - DFS(재귀호출 사용)
class Solution:
def dfs(self, grid, row, col):
grid[row][col] = '0'
directions = [(row-1, col), (row+1, col), (row, col-1), (row, col+1)]
for drow, dcol in directions:
if drow >= 0 and dcol >= 0 and drow < len(grid) and dcol < len(grid[drow]) and grid[drow][dcol] == "1":
self.dfs(grid, drow, dcol)
def numIslands(self, grid):
islands = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == "1":
self.dfs(grid, row, col)
islands += 1
return islands
sol = Solution()
print(sol.numIslands(preGrid))
재귀호출을 한단계씩 디버깅 해본 결과
preGrid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","1"],
["0","0","1","1","0"]
]
endGrid = [
["0", "0", "0", "0"],
["0", "0", "0", "0"],
["0", "0"],
["0"],
]
leetcode
https://leetcode.com/problems/number-of-islands/