Number of Islands - LeetCode

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

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
def numIslands(grid):
    # 함수 안에 함수를 넣어서 grid 사용 가능
    def dfs(x, y):
        if 0 <= x < len(grid) and 0 <= y < len(grid[0]):
            if grid[x][y] == '1':
                grid[x][y] = 'v'
                dfs(x - 1, y)
                dfs(x + 1, y)
                dfs(x, y - 1)
                dfs(x, y + 1)
                return True
        return False
 
    count = 0
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if dfs(i, j):
                count += 1
    return count
 
 
grid = [
    ["1""1""0""0""0"],
    ["1""1""0""0""0"],
    ["0""0""1""0""0"],
    ["0""0""0""1""1"]
]
numIslands(grid)
cs

방문 처리를 위해 따로 visited배열을 만들지 않아도 되는 문제이다.
함수 안에 함수를 선언했기 때문에 global없이 grid배열을 사용했다.

+ Recent posts