LeetCode

200. Number of Islands

zhelddustmq 2024. 7. 16. 17:11

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 lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

 

Example 1:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

 

 

code by python:




class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
        rows = len(grid)
        cols = len(grid[0])
        cnt = 0

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] != '1':
                    continue

                cnt += 1
                stack = [(row, col)]
                while stack:
                    x, y = stack.pop()
                    grid[x][y] = '0'
                    for i in range(4):
                        nx = x + dx[i]
                        ny = y + dy[i]
                        if nx < 0 or nx >= rows or ny < 0 or ny >= cols or grid[nx][ny] != '1':
                            continue
                        stack.append((nx, ny))
        return cnt





'LeetCode' 카테고리의 다른 글

704. Binary Search  (0) 2024.07.23
973. K Closest Points to Origin(with. HashTable)  (2) 2024.07.23
234. Palindrome Linked List  (0) 2024.07.15
215. Kth Largest Element in an Array  (0) 2024.07.15
20. Valid Parentheses  (0) 2024.07.12