접근
- 오히려 easy난이도보다 쉬운 문제인 것 같다
- 제공되는 자료형이 숫자가 아니라 문자임을 감안하지 않아 조금 고민
- 일반적인 방법의 코드도 숙지하는 것이 중요해 보임
문제
https://leetcode.com/problems/number-of-islands/description/
솔루션
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
answer = 0
ROW_length = len(grid)
COL_length = len(grid[0])
visited = [[False for _ in range(COL_length)] for _ in range(ROW_length)]
def dfs(ROW, COL):
# update this point as visited point
visited[ROW][COL] = True
# check left side
if COL > 0 and grid[ROW][COL-1] == '1' and \
visited[ROW][COL-1] == False:
dfs(ROW, COL-1)
# check right side
if COL < COL_length-1 and grid[ROW][COL+1] == '1' and \
visited[ROW][COL+1] == False:
dfs(ROW, COL+1)
# check up side
if ROW > 0 and grid[ROW-1][COL] == '1' and \
visited[ROW-1][COL] == False:
dfs(ROW-1, COL)
# check bottom side
if ROW < ROW_length-1 and grid[ROW+1][COL] == '1' and \
visited[ROW+1][COL] == False:
dfs(ROW+1, COL)
for r in range(ROW_length):
for c in range(COL_length):
if visited[r][c] == False and \
grid[r][c] == '1':
answer += 1
dfs(r,c)
return answer
'컴퓨터공학 & 정보통신 > 알고리즘 문제 풀이' 카테고리의 다른 글
[LeetCode] 36. Valid Sudoku (0) | 2023.03.31 |
---|---|
[LeetCode] 79. Word Search (0) | 2023.03.26 |
[LeetCode] 463. Island Perimeter (0) | 2023.03.25 |
[LeetCode] 131. Palindrome Partitioning (0) | 2023.03.23 |
[LeetCode] 46. Permutations (0) | 2023.03.21 |