LeetCode Number of Islands (JavaScript), DFS

2026. 1. 27. 17:03·코딩테스트/LeetCode

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

문제 설명

더보기

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'.

문제 풀이

dfs를 이용하여 접근

- 2중 for문을 돌며 '1'인 위치에 dfs를 검사 및 answer 1증가 -> 이어진 경로 탐색하기 위해

- dfs 함수 : 상, 하, 좌, 우 기준 연결된 모든 지역 검사 및 지나온 구역 '0'으로 초기화

- 최종적으로 answer 리턴

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
    let answer = 0;
    let direction = [
        [0, 1],
        [1, 0],
        [-1, 0],
        [0, -1]
    ];
    
    function dfs(y, x) {
        grid[y][x] = '0';

        for (const [dx, dy] of direction) {
            const mx = x + dx;
            const my = y + dy;

            if (
                mx >= 0 && mx < grid[0].length && 
                my >= 0 && my < grid.length &&
                grid[my][mx] === '1'
            ) {
                dfs(my, mx);
            }
        }
    }

    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === '1') {
                dfs(i, j);
                answer++;
            }
        }
    }

    return answer;
};

결론

기본적인 dfs 문제

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Valid Palindrome (JavaScript)  (0) 2026.01.26
LeetCode Best Time to Buy and Sell Stock (JavaScript)  (0) 2025.12.28
LeetCode Decode Ways (JavaScript), (DFS, Memoization)  (0) 2025.12.22
LeetCode Triangle (JavaScript)  (0) 2025.12.19
LeetCode Subsets ll (JavaScript), backtracking  (0) 2025.12.18
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Valid Palindrome (JavaScript)
  • LeetCode Best Time to Buy and Sell Stock (JavaScript)
  • LeetCode Decode Ways (JavaScript), (DFS, Memoization)
  • LeetCode Triangle (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (218)
      • 프론트엔드 (65)
        • JavaScript (52)
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (131)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (42)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Number of Islands (JavaScript), DFS
상단으로

티스토리툴바