© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
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 assume all four edges of the grid are all surrounded by water.
Example 1:
Example 2:
Constraints:
grid[i][j] is '0' or '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
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
const numIslands = (grid) => {
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
const m = grid.length;
const n = grid[0].length;
const visited = Array.from({length: m}, () => Array(n).fill(false));
let answer = 0;
const checkRange = (x, y) => {
if(x >= 0 && x < m && y >= 0 && y < n){
return true;
}
return false;
}
const dfs = (x, y) => {
for(let i = 0; i < 4; i++){
const nx = x + dx[i];
const ny = y + dy[i];
if(checkRange(nx, ny) && !visited[nx][ny] && grid[nx][ny] == "1"){
visited[nx][ny] = true;
dfs(nx, ny);
}
}
}
for(let i = 0; i < m; i++){
for(let j = 0; j < n; j++){
if(grid[i][j] == "1" && !visited[i][j]){
visited[i][j] = true;
dfs(i, j);
answer++;
}
}
}
return answer;
};const numIslands = (grid) => {
const bfs = (x, y) => {
const directions = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];
const queue = [];
queue.push([x, y]);
while (queue.length) {
const [x, y] = queue.shift();
if (!grid[x][y]) continue;
grid[x][y] = 0;
for (let i = 0; i < 4; i += 1) {
const [dx, dy] = directions[i];
const nx = x + dx;
const ny = y + dy;
if (
nx >= 0 &&
nx < rowLength &&
ny >= 0 &&
ny < colLength &&
grid[nx][ny] === '1'
) {
queue.push([nx, ny]);
}
}
}
};
let isLandCount = 0;
const rowLength = grid.length;
const colLength = grid[0].length;
for (let i = 0; i < rowLength; i += 1) {
for (let j = 0; j < colLength; j += 1) {
const now = grid[i][j];
if (now === '1') {
bfs(i, j);
isLandCount += 1;
}
}
}
return isLandCount;
};var numIslands = function(grid) {
const m = grid.length;
const n = grid[0].length;
let answer = 0;
const canGo = (x, y) => {
return x < m && y < n && x >= 0 && y >= 0;
}
const dfs = (x, y) => {
if(!canGo(x,y) || grid[x][y] === '0') {
return;
}
grid[x][y] = '0';
dfs(x + 1, y);
dfs(x - 1, y);
dfs(x, y + 1);
dfs(x, y - 1);
}
for(let i = 0; i < m; i++) {
for(let j = 0; j < n; j++) {
if(grid[i][j] === '1') {
answer++
dfs(i, j);
}
}
}
return answer;
};