π΅ λ¬Έμ
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"]
]))
'Algorithm' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[BOJ] 5427λ² λΆ - python (0) | 2023.07.10 |
---|---|
[BOJ] 2573λ² λΉμ° - python (0) | 2023.07.10 |
[νλ‘κ·Έλλ¨Έμ€] μκΆλν (2022 KAKAO BLIND RECRUITMENT) - Python (0) | 2023.03.06 |
[νλ‘κ·Έλλ¨Έμ€] νκ΄΄λμ§ μμ 건물 (2022 KAKAO BLIND RECRUITMENT) - Python (0) | 2023.03.06 |
[νλ‘κ·Έλλ¨Έμ€] νλ°° λ°°λ¬κ³Ό μκ±°νκΈ° (2023 KAKAO BLIND RECRUITMENT) - Python (2) | 2023.02.24 |