in the Given 2D Grid Map, '1' represents land and '0' represents water An island is Fromed By A group of connected lands, either Vertically or horizontally. Find the number of islands in the grid map
const input = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
// output: 3
const dfs = (graph, x, y) => {
if(
x < 0
|| graph.length <= x
|| y < 0
|| graph[x].length <= y
|| graph[x][y] === '0'
){
return false;
}
graph[x][y] = '0';
dfs(graph,x-1, y); //top
dfs(graph,x+1, y); //bottom
dfs(graph,x, y-1); //left
dfs(graph,x, y+1); //right
}
function solution(graph){
let result = 0;
if(graph.length === 0 || !graph){
return result;
}
for(let x = 0; x < graph.length; x++){
for(let y = 0; y < graph[x].length; y++){
if(graph[x][y] === '1'){
result += 1;
dfs(graph, x, y);
}
}
}
return result;
}
x,y;
while(stack.length > 0){
const [x, y] = stack.pop();
if(
x < 0 ||
x >= grid.length ||
y < 0 ||
y >= grid[x].length ||
grid[x][y] === '0'
){
continue;
}
grid[x][y] = '0';
for(const [mx, my] of map){
const newX = x+mx;
const newY = y+my;
stack.push([newX, newY]);
}
}
}
function solution(graph){
let result = 0;
if(graph.length === 0 || !graph){
return result;
}
for(let x = 0; x < graph.length; x++){
for(let y = 0; y < graph[x].length; y++){
if(graph[x][y] === '1'){
result += 1;
dfs(graph, x, y);
}
}
}
return result;
}">
function dfs(grid, x, y){ const map = [ [-1,0], // top [1, 0], //bottom [0, -1], //left [0, 1] //right ] const stack = [[x,y]]; while(stack.length > 0){ const [x, y] = stack.pop(); if( x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] === '0' ){ continue; } grid[x][y] = '0'; for(const [mx, my] of map){ const newX = x+mx; const newY = y+my; stack.push([newX, newY]); } } } function solution(graph){ let result = 0; if(graph.length === 0 || !graph){ return result; } for(let x = 0; x < graph.length; x++){ for(let y = 0; y < graph[x].length; y++){ if(graph[x][y] === '1'){ result += 1; dfs(graph, x, y); } } } return result; }