Algorithm
[Leetcode] BFS/DFS - Number of Islands
메린지
2024. 2. 16. 02:52
리트코드를 시작했숨니다 우하하,,
시작은 항상 잼이써
매일매일 잔디를 심읍시다
[문제]
https://leetcode.com/problems/number-of-islands/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
[풀이]
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def dfs(cor):
cur_x, cur_y = cor[0], cor[1]
if cur_x <0 or cur_x>=len(grid) or cur_y < 0 or cur_y >=len(grid[0]) or grid[cur_x][cur_y] == '0': return
grid[cur_x][cur_y] = '0'
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for x, y in directions:
nx, ny = x + cur_x, y + cur_y
dfs((nx, ny))
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs((i, j))
cnt += 1
return cnt
[내 Solution Link]
https://leetcode.com/problems/number-of-islands/solutions/4731310/1-graph-bfsdfs-numbers-of-islands/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com