|
| 1 | +## 문제 |
| 2 | + |
| 3 | +You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. |
| 4 | + |
| 5 | +Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). |
| 6 | + |
| 7 | +The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +Example: |
| 12 | +``` |
| 13 | +Input: |
| 14 | +[[0,1,0,0], |
| 15 | + [1,1,1,0], |
| 16 | + [0,1,0,0], |
| 17 | + [1,1,0,0]] |
| 18 | +
|
| 19 | +Output: 16 |
| 20 | +``` |
| 21 | + |
| 22 | +### 솔루션 |
| 23 | +1과 0의 경계선의 카운트를 구하는 문제다. for loop로 1인 경우에만 확장 시켜서, 위/아래/좌/우 가 0이 나오거나 배열을 벗어나면 1로 카운트 하게 한다. |
| 24 | +단, 그냥 하면 중복된 섬(문제에선 1이 섬이다.) 을 볼 수 있기 때문에 캐시를 두고, 이미 확인한 섬은 패스 한다. |
| 25 | + |
| 26 | +코드는 아래와 같다. |
| 27 | + |
| 28 | +```python3 |
| 29 | +class Solution: |
| 30 | + |
| 31 | + def dfs(self, i, j, grid, cache): |
| 32 | + |
| 33 | + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[i]): |
| 34 | + return 1 |
| 35 | + |
| 36 | + if grid[i][j] == 0: |
| 37 | + return 1 |
| 38 | + |
| 39 | + if (i, j) in cache: |
| 40 | + return 0 |
| 41 | + |
| 42 | + cache[(i, j)] = True |
| 43 | + |
| 44 | + ans = 0 |
| 45 | + ans += self.dfs(i, j - 1, grid, cache) |
| 46 | + ans += self.dfs(i, j + 1, grid, cache) |
| 47 | + ans += self.dfs(i + 1, j, grid, cache) |
| 48 | + ans += self.dfs(i - 1, j, grid, cache) |
| 49 | + |
| 50 | + return ans |
| 51 | + |
| 52 | + def islandPerimeter(self, grid): |
| 53 | + """ |
| 54 | + :type grid: List[List[int]] |
| 55 | + :rtype: int |
| 56 | + """ |
| 57 | + |
| 58 | + cache = dict() |
| 59 | + ans = 0 |
| 60 | + for i in range(len(grid)): |
| 61 | + for j in range(len(grid[i])): |
| 62 | + if grid[i][j] == 1: |
| 63 | + ans += self.dfs(i, j, grid, cache) |
| 64 | + |
| 65 | + return ans |
| 66 | +``` |
| 67 | + |
| 68 | +### 복잡도 |
| 69 | +공간 복잡도는 상수고, 시간 복잡도는 O(n) 이다. |
| 70 | +O(n) 인 이유는 캐시를 두어서 중복된 섬에서 확장 될 일이 없고, 최초에 for loop 만 있기 때문이다. (n 은 배열 길이 m*m) |
0 commit comments