| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- BFS
- SQL
- array
- Stack
- GenerativeAI
- 파이썬알고리즘
- Python3
- GenAI
- sql코테
- nlp
- 코드업
- 생성형AI
- 리트코드
- 슬라이딩윈도우
- Python
- 알고리즘
- dfs
- LeetCode
- Greedy
- heap
- 릿코드
- binary Tree
- 니트코드
- codeup
- stratascratch
- tree
- graph
- 파이썬
- 투포인터
- two-pointer
Archives
- Today
- Total
Tech for good
[Leetcode/DFS, BFS, Graph, Matrix] 200. Number of Islands 본문
IT/Computer Science
[Leetcode/DFS, BFS, Graph, Matrix] 200. Number of Islands
Diana Kang 2025. 8. 9. 07:00
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
n_rows, n_cols = len(grid), len(grid[0])
res = 0
visited = set()
def dfs(r, c):
visited.add((r,c))
neighbors = [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]
# check if visited or not
for n_r, n_c in neighbors:
if n_r in range(n_rows) and n_c in range(n_cols):
if grid[n_r][n_c] == "1" and (n_r, n_c) not in visited:
dfs(n_r, n_c)
# check grid one by one
for r in range(n_rows):
for c in range(n_cols):
# If the cell is land and not visited, it's a new island
if grid[r][c] == "1" and (r,c) not in visited:
# # Explore the entire island using DFS
dfs(r,c)
# # Increase the island count
res += 1
return res'IT > Computer Science' 카테고리의 다른 글
| [Codepath/BFS, Graph] Count Connected Components (0) | 2025.08.12 |
|---|---|
| [Codepath/BFS, Graph] Find Path (0) | 2025.08.12 |
| [Leetcode/DFS, BFS, Graph] 1971. Find if Path Exists in Graph (0) | 2025.08.08 |
| [Leetcode/Array, Hash Table, Graph] 997. Find the Town Judge (0) | 2025.08.08 |
| [HackerRank] Inorder Traversal of Binary Tree (0) | 2025.08.04 |