Skip to content

Instantly share code, notes, and snippets.

@tombaranowicz
Created October 12, 2019 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombaranowicz/3a5dc685ae89c7562e2626e75ddc4922 to your computer and use it in GitHub Desktop.
Save tombaranowicz/3a5dc685ae89c7562e2626e75ddc4922 to your computer and use it in GitHub Desktop.
Google Coding Interviews Number of Islands (LeetCode) and explanation. One of Google's most commonly asked interview questions according to LeetCode. This coding interview question is commonly asked by companies like: Google, Facebook, Snapchat, Amazon, Uber, LinkedIn, Microsoft, Apple and many others.
/**
* @param {character[][]} grid
* @return {number}
*/
var dfs = function(grid, i, j) {
const w = grid.length;
const h = grid[0].length;
if ( i >= 0 && i < w && j >= 0 && j < h && grid[i][j] == '1') {
grid[i][j] = '0'
dfs(grid, i+1, j); //right
dfs(grid, i-1, j); //left
dfs(grid, i, j+1); //below
dfs(grid, i, j-1); //above
}
}
var numIslands = function(grid) {
let islands = 0;
if(grid.length == 0) {
return 0;
}
const w = grid.length;
const h = grid[0].length;
for (let i=0; i<w; i++) {
for(let j=0; j<h; j++) {
const char = grid[i][j];
if (char == '1') {
dfs(grid, i, j);
islands += 1;
}
}
}
return islands;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment