-
LeetCode : 200. Number of Islands🐳Dev/LeetCode 2023. 5. 8. 16:02
문제
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.
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is '0' or '1'.
풀이
- numIsLands 함수에서는 grid의 모든 값을 돌면서, 해당 위치가 land를 의미하는 ‘1’이 라면 아래 search 함수를 실행함
- search는 재귀함수
- 인덱스가 범위 밖이거나 값이 1이 아닌 경우는 return을 함
- 그 외에는 해당 인덱스에 임의의 값(2)를 넣어주고, 인덱스를 중심으로 상하좌우로 search 함수를 호출함
- 이미 방문한 위치에 1이 아닌 임의의 값을 넣어 뒀으므로, 중복된 섬 찾기는 피할 수 있음
'🐳Dev > LeetCode' 카테고리의 다른 글
LeetCode : 1484. Group Sold Products By The Date (0) 2023.05.13 LeetCode : 235. Lowest Common Ancestor of a Binary Search Tree (0) 2023.05.05 LeetCode : 98. Validate Binary Search Tree (0) 2023.05.03 LeetCode : 102. Binary Tree Level Order Traversal (0) 2023.05.01 LeetCode : 142. Linked List Cycle II (0) 2023.04.26