본문 바로가기

리트코드/midium

[리트코드] 200. Number of Islands - js (DFS)

반응형

1. 문제

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

 

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

2. 코드

요소의 값이 숫자가 아니라 문자다.. 

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
	let count = 0;
	
	const isIsland = (i, j) => {
		if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] === "0") {
			return;
		}
		
		grid[i][j] = "0"; // 연결된 요소들을 전부 0 처리(for 문 내 if 문에서 걸려 탐색되지 않도록)
		
		isIsland(i + 1, j); 
		isIsland(i - 1, j); 
		isIsland(i, j + 1); 
		isIsland(i, j - 1); 
	}

	for (let i = 0; i < grid.length; i++) {
		for (let j = 0; j < grid[i].length; j++) {
			if (grid[i][j] === "1") {
				count += 1;
				isIsland(i, j);
			}
		}
	}
	
	return count;
};
반응형