[Leetcode] DFS/BFS - Number of Islands

2023. 12. 8. 16:04·프로그래밍/Python

문제 

 

https://leetcode.com/problems/number-of-islands/

 

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

 

 

gird는 "1"(land)과 "0"(water)으로 이루어진 지도를 표현하는 m x n 이차원배열이다. 이 지도에 표시된 섬들의 총 갯수를 반환하시오. 섬이란 수평과 수직으로 땅이 연결되어 있고 주변은 물로 둘러쌓여있는 것을 말한다. 또한, grid의 네개의 가장자리는 모두 물로 둘러쌓여있다고 가정하고 문제를 해결하라.

 

 

제약조건

 

1. m == grid.length

2. n == grid[i].length

3. 1 <= m,n <= 300 → 300x300은 900으로 약 10^5이므로 O(n^2) 미만 시간복잡도로 풀어야한다는 단서이다.

4. grid[i][i] is '0' or '1'

 

 

구현

 

→ BFS

from collections import deque

def numIslands(grid):
    numsOfIslands = 0
    rowLength = len(grid) #4
    colLength = len(grid[0]) #5
    visited = [[False] * colLength for _ in range(rowLength)]

    def bfs(r,c):
        gx = [-1, 1, 0, 0]
        gy = [0, 0, -1, 1]
        q = deque()
        q.append((r,c))
        visited[r][c] = True
        while q:
            cx, cy = q.popleft()
            for i in range(4):
                next_x = cx + gx[i]
                next_y = cy + gy[i]
                if 0 <= next_x and next_x < rowLength and 0 <= next_y and next_y < colLength:
                    if grid[next_x][next_y] == "1" and visited[next_x][next_y] == False:
                        visited[next_x][next_y] = True
                        q.append((next_x, next_y))
        
        
    for i in range(rowLength):
        for j in range(colLength):
            if grid[i][j] == "1" and visited[i][j] == False:
                    bfs(i, j)
                    numsOfIslands += 1

    return numsOfIslands

 

 

→ DFS

def numOfIslands(grid):
    num = 0
    lowLen = len(grid)
    colLen = len(grid[0])
    visited = [[False] * colLen for _ in range(lowLen)]

    def dfs(r, c):
        dx = [-1,1,0,0]
        dy = [0,0,-1,1]
        visited[r][c] = True
        for i in range(4):
            nx = r + dx[i]
            ny = c + dy[i]
            if 0 <= nx and nx < lowLen and 0 <= ny and ny < colLen:
                if grid[nx][ny] == "1" and visited[nx][ny] == False:
                    dfs(nx, ny)
    
    for i in range(lowLen):
        for j in range(colLen):
            if grid[i][j] == "1" and visited[i][j] == False:
                dfs(i,j)
                num += 1
    return num

'프로그래밍 > Python' 카테고리의 다른 글

[프로그래머스 Lv.1] - 둘만의 암호  (0) 2024.04.26
[프로그래머스 Lv.1] - 카드뭉치 (리스트 정렬여부를 체크하는 효율적인 방법)  (2) 2024.01.07
[프로그래머스 알고리즘 Kit] 스택/큐 - 다리를 지나는 트럭  (0) 2023.11.05
[프로그래머스 알고리즘 Kit] 스택/큐 - 주식가격  (0) 2023.10.30
[Leetcode] 이중연결리스트 - Design Browser History  (0) 2023.10.26
'프로그래밍/Python' 카테고리의 다른 글
  • [프로그래머스 Lv.1] - 둘만의 암호
  • [프로그래머스 Lv.1] - 카드뭉치 (리스트 정렬여부를 체크하는 효율적인 방법)
  • [프로그래머스 알고리즘 Kit] 스택/큐 - 다리를 지나는 트럭
  • [프로그래머스 알고리즘 Kit] 스택/큐 - 주식가격
횰쓰
횰쓰
개발 성장 블로그입니다
  • 횰쓰
    횰쓰토리
    횰쓰
  • 전체
    오늘
    어제
    • 분류 전체보기
      • CS 공부
        • 운영체제
        • 네트워크
        • 컴퓨터구조
        • 데이터베이스
        • 알고리즘
        • 소프트웨어공학
        • 자료구조
        • 웹
      • 프로그래밍
        • Python
        • NodeJS
      • 프로젝트
        • React 프로젝트
      • 개발도구
        • Git
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    4 way handshake
    자가균형 이진탐색트리
    RB Tree
    3 Way Handshake
    AVL트리
    tcp
    RB트리
    프로세스 주소공간
    포화이진트리
    전이진트리
    한국사능력검정시험 심화
    리스트정렬여부
    둘만의 암호
    Max힙
    큐
    멀티 프로세스
    스택
    카드뭉치
    chrome
    경쟁상태(Race Condition)
    Push-force
    페이지 교체
    최태성인강
    SQL/NOSQL
    Sync/Async
    운영체제
    이진탐색트리
    멀티 스레드
    Git
    Min힙
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
횰쓰
[Leetcode] DFS/BFS - Number of Islands
상단으로

티스토리툴바