Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Til
- 판다스
- 부트캠프후기
- 유데미코리아
- 취업부트캠프
- 코딩테스트
- 데이터프레임
- 태블로
- 넘파이
- 브루트포스 알고리즘
- pandas
- 데이터시각화
- matplotlb
- 그리디 알고리즘
- 유데미큐레이션
- 유데미
- 데이터드리븐
- Tableau
- 시각화
- 정렬
- ndarray
- python
- 스타터스부트캠프
- DataFrame
- numpy
- Leetcode
- 백준
- 데이터분석
- 유데미부트캠프
- 파이썬
Archives
- Today
- Total
Diary, Data, IT
[LeetCode] 200. Number of Islands - Python 본문
[LeetCode] 200. Number of Islands - Python
Number of Islands - LeetCode
Can you solve this real interview question? 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 l
leetcode.com
문제
1을 육지로, 0을 물로 가정한 2D 그리드 맵이 주어졌을 때, 섬의 개수를 계산하세요.
즉 연결되어있는 1의 덩어리 수를 구하는 문제입니다.
아이디어
DFS 그래프 탐색을 이용해서 해결하는 대표적인 문제이다. 다음과 같은 알고리즘으로 코드를 작성하여 문제를 해결했다.
1) 각 위치(i, j)를 순서대로 탐색하면서 땅(1)인지 확인하고, 동서남북으로 이동하면서 땅이 아니라면 함수를 종료한다.
함수가 종료되면 섬 1개를 찾았다는 의미로 count +=1를 진행한다.
2) 동서남북으로 이동하며 탐색하는 과정을 구현하기 위해 재귀함수를 사용한다.
3) 탐색 과정에서 한번 확인한 땅은 0으로 설정해준다. 그래야 같은 지역을 재탐색하여 중복되는 경우를 막아준다.
코드
def numIslands(grid: list[list[str]]) -> int:
def dfs(i, j):
#땅이 아니라면 함수를 끝내기
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != '1': #grid[i][j] == '0'은 오류
return
#땅이든 아니든 탐색했으면 0으로 설정
grid[i][j] = 0
#땅이라면, 상하좌우 탐색
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)
#한번 끝나면 지나온 길은 0으로 바꾸므로 중복되지 않음, 따라서 함수가 끝나면 바로 1을 더해줘도 ok
count += 1
return count
'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 17. Letter Combinations of a Phone Number - Python (0) | 2023.04.15 |
---|---|
[LeetCode] 3. Longest Substring Without Repeating Characters - Python (0) | 2023.04.14 |
[LeetCode] 937. Reorder Data in Log Files - Python (0) | 2023.04.11 |
[LeetCode] 819. Most Common Word - Python (0) | 2023.04.11 |
[LeetCode] 344. Reverse String - Python (0) | 2023.04.11 |