Given an m x n 2d grid 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.
모르겠어서 루션이 보고 제 스탈로 각색했읍니다.
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def isIsland(i, j):
grid[i][j] = '0'
if i-1 > =0 and grid[i-1][j] == '1':
isIsland(i-1, j)
if i+1 < len(grid) and grid[i+1][j] == '1':
isIsland(i+1, j)
if j-1 > =0 and grid[i][j-1] == '1':
isIsland(i, j-1)
if j+1 < len(grid[i]) and grid[i][j+1] == '1':
isIsland(i, j+1)
count = 0
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] == '1':
count += 1
isIsland(i, j)
return count
isIsland 함수를 만들어서 인접한 곳에 1이 있는지 확인하고 방문한 곳의 값은 0으로 바꿔주었다.
첨엔 전에 풀었던 36번 스도쿠 문제를 응용해야하나...
아님 n중 for 문 써야되나 했지만..
재귀가 말끔하게 해결~~