Algorithm

[leetcode] 200. number of Islands

lerrybe 2023. 5. 31. 23:09

🌡 문제


 

 

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

 

 

πŸš€ 풀이


배열을 λ„λŠ”λ° λ§Œμ•½ μœ‘μ§€κ°€ μ•„λ‹ˆλΌλ©΄ ν•΄λ‹Ήν•˜λŠ” μ§€μ μ—μ„œμ˜ 탐색을 μ‹œμž‘ν•˜μ§€ μ•Šκ³ , μœ‘μ§€λΌλ©΄ 탐색을 μ‹œμž‘ν•˜μ—¬ μ—°κ²°λœ μœ‘μ§€λ₯Ό 감지, DFSκ°€ λλ‚œ 후에 μ„¬μ˜ 개수λ₯Ό ν•˜λ‚˜ μ¦κ°€ν•˜μ—¬ 총 μ„¬μ˜ 개수λ₯Ό μΉ΄μš΄νŒ…ν•©λ‹ˆλ‹€. DFS κ³Όμ • λ‚΄μ—μ„œλŠ” μ€‘λ³΅λœ μΉ΄μš΄νŒ…μ„ 막기 μœ„ν•΄ λ°©λ¬Έν•œ μœ‘μ§€λŠ” 기쑴의 μœ‘μ§€ ("1")μ™€λŠ” λ‹€λ₯΄κ²Œ λ§ˆν‚Ήμ„ ν•΄μ€λ‹ˆλ‹€. (κΌ­ "V"κ°€ μ•„λ‹ˆμ–΄λ„ μƒκ΄€μ—†μŠ΅λ‹ˆλ‹€. "1"만 μ•„λ‹ˆλ©΄ λ©λ‹ˆλ‹€.) visited 배열을 μ΄μš©ν•΄ λ°©λ¬Έ μ—¬λΆ€λ₯Ό κΈ°λ‘ν•˜μ§€ μ•Šμ€ μ΄μœ λŠ” μΆ”κ°€ 곡간을 μ‚¬μš©ν•˜μ§€ μ•Šκ³  grid 배열을 μˆ˜μ •ν•˜λŠ” κ²ƒμœΌλ‘œλ„ λ°©λ¬Έ μ—¬λΆ€ 감지가 μΆ©λΆ„νžˆ λ˜μ—ˆκΈ° λ•Œλ¬ΈμΈλ° 원본 ν›Όμ†μ˜ μš°λ €κ°€ μžˆλ‹€λ©΄ visitedλ₯Ό λ‘¬μ„œ λ°©λ¬Έ μ—¬λΆ€ λ§ˆν‚Ήμ„ 해도 쒋을 것 κ°™μŠ΅λ‹ˆλ‹€. 


πŸ’‘ ν’€μ΄ μ½”λ“œλŠ” μ•„λž˜μ™€ κ°™μŠ΅λ‹ˆλ‹€. 

LAND = "1"
MARK = "V"

dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]

def dfs(grid, x, y):
    if x < 0 or x > len(grid) - 1 or y < 0 or y > len(grid[0]) - 1:
        return
    if grid[x][y] != LAND:
        return
    
    grid[x][y] = MARK
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx <= len(grid) - 1 and 0 <= ny <= len(grid[0]) - 1:
            dfs(grid, nx, ny)

def numIslands(grid):
    cnt = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == LAND:
                dfs(grid, i, j)
                cnt += 1
    return cnt


print(numIslands([
    ["1","1","1","1","0"],
    ["1","1","0","1","0"],
    ["1","1","0","0","0"],
    ["0","0","0","0","0"]
]))
print(numIslands([
    ["1","1","0","0","0"],
    ["1","1","0","0","0"],
    ["0","0","1","0","0"],
    ["0","0","0","1","1"]
]))