waveofmymind
기록하는 습관
waveofmymind
전체 방문자
오늘
어제
  • 분류 전체보기 (124)
    • 📝 정리 (5)
    • 🌊TIL (9)
    • 💻CS (1)
      • 자료구조 (1)
    • 📙Language (9)
      • ☕Java (6)
      • 🤖Kotlin (3)
    • 🍃Spring (28)
    • 👨🏻‍💻알고리즘 (67)
      • 프로그래머스 (59)
      • 백준 (3)
    • 👷DevOps (4)
      • 🐳Docker (2)
      • 🤵Jenkins (1)

블로그 메뉴

  • 홈
  • Spring
  • Java
  • 알고리즘

공지사항

인기 글

태그

  • 다이나믹 프로그래밍
  • sql
  • 스프링
  • kotest
  • 트랜잭션
  • CORS
  • 스택
  • resultset
  • Spring Security
  • BFS
  • SpringAOP
  • 코틀린
  • 트랜잭션 전파
  • Open AI
  • 통합테스트
  • 힙
  • 스프링 부트
  • chat GPT
  • LeetCode
  • Connection
  • spring
  • 챗GPT
  • AOP
  • 스프링 시큐리티
  • JDBC
  • til
  • 완전탐색
  • mybatis
  • kotlin
  • spring boot

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
waveofmymind

기록하는 습관

[LeetCode] 200. Number of Islands
👨🏻‍💻알고리즘

[LeetCode] 200. Number of Islands

2023. 2. 24. 00:32

문제 링크: https://leetcode.com/problems/number-of-islands/description/

 

Number of Islands - LeetCode

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 lands horizontally or vertically. You may ass

leetcode.com

코드

from collections import deque

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        cnt = 0
        row = len(grid)
        col = len(grid[0])
        visited = [[False]*col for _ in range(row)]
        q=deque()
        dx = [-1,1,0,0]
        dy = [0,0,-1,1]
        for i in range(row):
            for j in range(col):
                if grid[i][j] == "1" and not visited[i][j]:
                    visited[i][j] = True
                    cnt += 1
                    q.append((i,j))
                    while q:
                        x,y = q.popleft()
                        for t in range(4):
                            nx = x+dx[t]
                            ny = y + dy[t]
                            if 0<=nx<row and 0<= ny < col and grid[nx][ny] == "1" and not visited[nx][ny]:
                                visited[nx][ny] = True
                                q.append((nx,ny))

        return cnt

 

풀이

  • 기본적인 BFS문제이다.
  • grid[i][j]를 탐색하다 아직 방문하지 않았으면서, 1일때 q에 들어가게 된다.
  • q에 들어갈때가 섬의 시작지점이므로 cnt를 1 증가시킨다.

'👨🏻‍💻알고리즘' 카테고리의 다른 글

[LeetCode] 70. Climbing Stairs  (0) 2023.02.28
[LeetCode] 841. Keys and Rooms  (0) 2023.02.24
[LeetCode] 1091. Shortest Path in Binary Matrix  (0) 2023.02.24
[LeetCode] Medium. Daily Temperatures  (1) 2023.02.16
    '👨🏻‍💻알고리즘' 카테고리의 다른 글
    • [LeetCode] 70. Climbing Stairs
    • [LeetCode] 841. Keys and Rooms
    • [LeetCode] 1091. Shortest Path in Binary Matrix
    • [LeetCode] Medium. Daily Temperatures
    waveofmymind
    waveofmymind

    티스토리툴바