Skip to content

Instantly share code, notes, and snippets.

@hamannjames
Last active August 17, 2017 03:53
Show Gist options
  • Save hamannjames/9cf93e088553cad5f35d5dc9dc3906d8 to your computer and use it in GitHub Desktop.
Save hamannjames/9cf93e088553cad5f35d5dc9dc3906d8 to your computer and use it in GitHub Desktop.
Mapping land
/*
So let's say we're writing a program that will find the number of islands given a picture from a satellite.
The picture has already been pre-processed and encoded to a 2D matrix where 1 means land. And 0 means water.
How many islands are there?
*/
// It is safe to assume the input will be an array of arrays and that the values are always 0, 1
// It is worth noting that every 1 does not mean an individual island. 1's can connect to form a single landmass
/*
{{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}}
*/
function mapIsland(arr) {
let landHash = {};
let landCount = 0;
let queue = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === 1) {
if (!checkMap(i + '-' + j)) {
walkLand([i, j]);
landCount++;
}
}
}
}
function checkMap(index) {
if (landHash[index]) {
return true;
}
return false;
}
function walkLand(pair) {
let i = pair[0];
let j = pair[1];
landHash[i + '-' + j] = 1;
console.log(landHash);
if (!(j === arr.length - 1)) {
if (arr[i][j + 1]) {
queue.push([i, j + 1]);
}
}
if (!(j === arr.length - 1) && !(i === arr.length - 1)) {
if (arr[i + 1][j + 1]) {
queue.push([i + 1, j + 1]);
}
}
if (!(i === arr.length - 1)) {
if (arr[i + 1][j]) {
queue.push([i + 1, j]);
}
if (!(j === 0)) {
if (arr[i + 1][j - 1]) {
queue.push([i + 1, j - 1]);
}
}
}
if (queue.length) {
walkLand(queue.shift());
}
else {
return;
}
}
return landCount;
}
@hamannjames
Copy link
Author

This currently exceeds call stack size I put this up to get feedback from other communities. Working on an implementation that uses queue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment