Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="row">
  <div class="col">
    This visulization is part of: <a href="https://livefiredev.com/number-of-islands-leetcode-explained-with-animations-visualizations">Number of Islands - LeetCode Explained (With Animations & Visualizations)</a>
  </div>
</div>

<div>
  <div id="traversal_mode_card">
    <div style="margin-bottom: 10px;">
                <label>Ratio Of Land To Water</label>
      &nbsp;&nbsp;
      <input type="range" id="land_to_water_ratio" min="1" max="100" value="20">
    </div>
  </div>
</div>

<div class="row">
  <div class="col algo_block">
    <h3>Number Of Islands Found DFS: <span id="number_of_islands_found_dfs">0</span></h3>
    <div id="world_canvas_dfs">
    </div>
  </div>

  <div class="col algo_block">
    <h3>Number Of Islands Found BFS: <span id="number_of_islands_found_bfs">0</span></h3>
    <div id="world_canvas_bfs">
    </div>
  </div>

</div>
<button class="button-30" role="button" id="playButton">Play</button>
&nbsp;
<button class="button-30" role="button" id="nextButton">Next</button>
              
            
!

CSS

              
                body {
  font-family: 'Roboto', sans-serif;
}

/* CSS */
.button-30 {
  align-items: center;
  appearance: none;
  background-color: #FCFCFD;
  border-radius: 4px;
  border-width: 0;
  box-shadow: rgba(45, 35, 66, 0.4) 0 2px 4px, rgba(45, 35, 66, 0.3) 0 7px 13px -3px, #D6D6E7 0 -3px 0 inset;
  box-sizing: border-box;
  color: #36395A;
  cursor: pointer;
  display: inline-flex;
  font-family: "JetBrains Mono", monospace;
  height: 48px;
  justify-content: center;
  line-height: 1;
  list-style: none;
  overflow: hidden;
  padding-left: 16px;
  padding-right: 16px;
  position: relative;
  text-align: left;
  text-decoration: none;
  transition: box-shadow .15s, transform .15s;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  white-space: nowrap;
  will-change: box-shadow, transform;
  font-size: 18px;
}

.button-30:focus {
  box-shadow: #D6D6E7 0 0 0 1.5px inset, rgba(45, 35, 66, 0.4) 0 2px 4px, rgba(45, 35, 66, 0.3) 0 7px 13px -3px, #D6D6E7 0 -3px 0 inset;
}

.button-30:hover {
  box-shadow: rgba(45, 35, 66, 0.4) 0 4px 8px, rgba(45, 35, 66, 0.3) 0 7px 13px -3px, #D6D6E7 0 -3px 0 inset;
  transform: translateY(-2px);
}

.button-30:active {
  box-shadow: #D6D6E7 0 3px 7px inset;
  transform: translateY(2px);
}

#traversal_mode_card {
  background-color: #FCFCFD;
  padding: 10px;
  border-radius: 4px;
  box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;
  margin-bottom: 10px;
  display: inline-block;
}

#traversal_mode_card label {
  font-weight: bold;
}

.row {
  display: flex;
  flex-wrap: wrap;
}

.col {
  flex: 1;
  padding: 10px;
}

.algo_block {
  box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;
  border: 0.5px solid lightgrey;
  padding: 10px;
  margin-bottom: 20px;
}
              
            
!

JS

              
                let blockSize = 20;
let worldSize = 20;
let landColor = "#8b624c";
let waterColor = "#7ee0e0";
let blockBeingPushedIntoFrontierColor = "#FFFD37";
let blockToIgnoreColor = "#baadad";
let conqueredLandColor = "#50C878";
let passingOverConqueredLandColor = "#b8e9c9";

const convertWorldToBlockSettingsArray = (world) => {
  let blockSettingsArray = [];

  world.forEach((subArray, subArrayIndex) => {
    let blockRow = [];
    subArray.forEach((subArrayElement, subArrayElementIndex) => {
      let x = subArrayElementIndex * blockSize;
      let y = subArrayIndex * blockSize;
      let color = subArrayElement === 0 ? waterColor : landColor;
      blockRow.push({ x, y, color });
    });
    blockSettingsArray.push(blockRow);
  });
  return blockSettingsArray;
};

let drawWorld = (worldAsBlockSettings, elementId) => {
  document.getElementById(elementId).innerHTML = "";
  let draw = SVG()
    .addTo(`#${elementId}`)
    .size(
      worldAsBlockSettings[0].length * blockSize,
      worldAsBlockSettings.length * blockSize
    );
  worldAsBlockSettings.forEach((subArray) => {
    subArray.forEach((blockSettings) => {
      draw
        .rect(blockSize, blockSize)
        .move(blockSettings.x, blockSettings.y)
        .fill(blockSettings.color);
    });
  });
};

const generateRandomPointOfLandOrWater = () => {
  let randomNumberBetweenZeroAndHundreds = Math.round(Math.random() * 100);
  let ratioOfLandToWater = document.getElementById("land_to_water_ratio").value;
  return randomNumberBetweenZeroAndHundreds < parseInt(ratioOfLandToWater)
    ? 1
    : 0;
};

const generateRandomWorld = (width, height) => {
  let world = [];
  for (let i = 0; i < height; i++) {
    let row = [];
    for (let j = 0; j < width; j++) {
      row.push(generateRandomPointOfLandOrWater());
    }
    world.push(row);
  }
  return world;
};

const changeBlockColorAndReDrawWorld = (
  world,
  elementId,
  subArrayIdx,
  elementInsideSubArrayIdx,
  newColor
) => {
  world[subArrayIdx][elementInsideSubArrayIdx].color = newColor;
  drawWorld(world, elementId);
};

const renderNumberOfIslandsFound = () => {
  document.getElementById(
    "number_of_islands_found_bfs"
  ).innerHTML = numberOfIslandsBFS;
  document.getElementById(
    "number_of_islands_found_dfs"
  ).innerHTML = numberOfIslandsDFS;
};

let bfsQueue = [];
let dfsStack = [];

let arrayThatHoldsTheBlocksToConquer = {
  bfs: bfsQueue,
  dfs: dfsStack
};

let canvasIds = {
  bfs: "world_canvas_bfs",
  dfs: "world_canvas_dfs"
};

let world = undefined;

let worldsAsBlockSettings = {
  bfs: undefined,
  dfs: undefined
};

let currentMode = {
  bfs: "find_land", // can also be: 'conquer_land'
  dfs: "find_land"
};

let currentTraversalIndexes = {
  bfs: {
    subArrayIdx: 0,
    subArrayElementIdx: 0
  },
  dfs: {
    subArrayIdx: 0,
    subArrayElementIdx: 0
  }
};

let blocksThatHaveBeenAddedToFrontier = {
  bfs: {},
  dfs: {}
};

let numberOfIslands = {
  bfs: 0,
  dfs: 0
};

const createDFSAndBFSWorlds = () => {
  world = generateRandomWorld(worldSize, worldSize);
  let worldAsBlockSettings = convertWorldToBlockSettingsArray(world);
  worldsAsBlockSettings["bfs"] = structuredClone(worldAsBlockSettings);
  worldsAsBlockSettings["dfs"] = structuredClone(worldAsBlockSettings);
  drawWorld(worldsAsBlockSettings["bfs"], canvasIds.bfs);
  drawWorld(worldsAsBlockSettings["dfs"], canvasIds.dfs);
};

createDFSAndBFSWorlds();

const visuallyShowThatCurrentWaterBlockIsExplored = (algo) => {
  let worldAsBlockSettings = worldsAsBlockSettings[algo];
  let worldElementId = canvasIds[algo];
  let currentBlock = currentTraversalIndexes[algo];
  changeBlockColorAndReDrawWorld(
    worldAsBlockSettings,
    worldElementId,
    currentBlock.subArrayIdx,
    currentBlock.subArrayElementIdx,
    blockToIgnoreColor
  );
};

const visuallyShowThatCurrentLandBlockIsConquered = (algo, blockToConquer) => {
  let worldAsBlockSettings = worldsAsBlockSettings[algo];
  let worldElementId = canvasIds[algo];
  changeBlockColorAndReDrawWorld(
    worldAsBlockSettings,
    worldElementId,
    blockToConquer.subArrayIdx,
    blockToConquer.subArrayElementIdx,
    conqueredLandColor
  );
};

const visuallyShowThatWeArePassingOverConqueredLandButAreIgnoringTheBlock = (
  algo,
  block
) => {
  let worldAsBlockSettings = worldsAsBlockSettings[algo];
  let worldElementId = canvasIds[algo];
  changeBlockColorAndReDrawWorld(
    worldAsBlockSettings,
    worldElementId,
    block.subArrayIdx,
    block.subArrayElementIdx,
    passingOverConqueredLandColor
  );
  setTimeout(() => {
    changeBlockColorAndReDrawWorld(
      worldAsBlockSettings,
      worldElementId,
      block.subArrayIdx,
      block.subArrayElementIdx,
      conqueredLandColor
    );
  }, 25);
};

const updateNumberOfIslandsCount = (algo) => {
  numberOfIslands[algo] += 1;
  document.getElementById(`number_of_islands_found_${algo}`).innerText =
    numberOfIslands[algo];
};

const visuallyShowThatCurrentLandBlockIsAddedToTheFrontier = (
  algo,
  blockToAddToFrontier
) => {
  let worldAsBlockSettings = worldsAsBlockSettings[algo];
  let worldElementId = canvasIds[algo];
  changeBlockColorAndReDrawWorld(
    worldAsBlockSettings,
    worldElementId,
    blockToAddToFrontier.subArrayIdx,
    blockToAddToFrontier.subArrayElementIdx,
    blockBeingPushedIntoFrontierColor
  );
};

const whatsAtThisLocation = (objectWithIndexes) => {
  let currentValue =
    world[objectWithIndexes.subArrayIdx][objectWithIndexes.subArrayElementIdx];
  if (currentValue == 1) {
    return "land";
  } else {
    return "water";
  }
};

const moveToTheNextBlock = (algo) => {
  let currentBlock = currentTraversalIndexes[algo];
  // To do, we need to handle edge cases of
  // no more sub arrays and no more element in sub array

  let newSubArrayElementIdx = undefined;
  let newSubArrayIdx = undefined;
  if (currentBlock.subArrayElementIdx == worldSize - 1) {
    // We are at the end of the current sub-array
    // we need to move to the next one
    if (currentBlock.subArrayIdx == worldSize - 1) {
      // There is nowhere else to go
    } else {
      newSubArrayElementIdx = 0;
      newSubArrayIdx = currentBlock.subArrayIdx + 1;
    }
  } else {
    newSubArrayElementIdx = currentBlock.subArrayElementIdx + 1;
    newSubArrayIdx = currentBlock.subArrayIdx;
  }

  let newBlock = {
    subArrayIdx: newSubArrayIdx,
    subArrayElementIdx: newSubArrayElementIdx
  };

  currentTraversalIndexes[algo] = newBlock;
};

const getBlockToConquerDependingOnAlgo = (algo) => {
  let theArrayThatHoldsTheBlocksToConquer =
    arrayThatHoldsTheBlocksToConquer[algo];
  if (algo == "bfs") {
    return theArrayThatHoldsTheBlocksToConquer.shift();
  } else {
    return theArrayThatHoldsTheBlocksToConquer.pop();
  }
};

const addBlockToFrontier = (algo, block) => {
  blocksThatHaveBeenAddedToFrontier[algo][
    `${block.subArrayIdx},${block.subArrayElementIdx}`
  ] = true;
  visuallyShowThatCurrentLandBlockIsAddedToTheFrontier(algo, block);
  arrayThatHoldsTheBlocksToConquer[algo].push(block);
};

const isBlockAlreadyAddedToTheFrontier = (algo, block) => {
  return (
    blocksThatHaveBeenAddedToFrontier[algo][
      `${block.subArrayIdx},${block.subArrayElementIdx}`
    ] === true
  );
};

const canThisBlockExist = (block) => {
  if (block.subArrayIdx < 0) return false;
  if (block.subArrayElementIdx < 0) return false;
  if (block.subArrayIdx >= worldSize) return false;
  if (block.subArrayElementIdx >= worldSize) return false;
  return true;
};

const addBlocksThatCanBeConqueredFromThisBlockToTheFrontier = (
  algo,
  blockToConquer
) => {
  let blockAbove = {
    subArrayIdx: blockToConquer.subArrayIdx - 1,
    subArrayElementIdx: blockToConquer.subArrayElementIdx
  };

  let blockBelow = {
    subArrayIdx: blockToConquer.subArrayIdx + 1,
    subArrayElementIdx: blockToConquer.subArrayElementIdx
  };

  let blockToRight = {
    subArrayIdx: blockToConquer.subArrayIdx,
    subArrayElementIdx: blockToConquer.subArrayElementIdx + 1
  };

  let blockToLeft = {
    subArrayIdx: blockToConquer.subArrayIdx,
    subArrayElementIdx: blockToConquer.subArrayElementIdx - 1
  };

  let allPossibleBlocksToConquer = [
    blockAbove,
    blockBelow,
    blockToRight,
    blockToLeft
  ];

  let onlyBlocksThatCanExist = allPossibleBlocksToConquer.filter(
    canThisBlockExist
  );

  let blocksWithLand = onlyBlocksThatCanExist.filter((block) => {
    if (whatsAtThisLocation(block) == "land") {
      return true;
    } else {
      return false;
    }
  });

  let newUnvisitedBlocks = blocksWithLand.filter((block) => {
    return isBlockAlreadyAddedToTheFrontier(algo, block) == false;
  });

  newUnvisitedBlocks.forEach((block) => {
    addBlockToFrontier(algo, block);
  });
};

let conquerLand = (algo) => {
  let blockToConquer = getBlockToConquerDependingOnAlgo(algo);

  if (blockToConquer == undefined) {
    currentMode[algo] = "find_land";
    updateNumberOfIslandsCount(algo);
    moveToTheNextBlock(algo);
    return;
  }

  visuallyShowThatCurrentLandBlockIsConquered(algo, blockToConquer);
  addBlocksThatCanBeConqueredFromThisBlockToTheFrontier(algo, blockToConquer);
};

const goNext = (algo) => {
  let theCurrentMode = currentMode[algo];
  if (theCurrentMode == "find_land") {
    let currentTraversalIndex = currentTraversalIndexes[algo];

    if (currentTraversalIndex.subArrayIdx == undefined) {
      if (autoPlayIntervalId != undefined) {
        clearInterval(autoPlayIntervalId);
        autoPlayIntervalId = undefined;
      }
      return;
    }

    // If we have already explored this block
    // via land exploration we need to ignore this block
    if (isBlockAlreadyAddedToTheFrontier(algo, currentTraversalIndex) == true) {
      visuallyShowThatWeArePassingOverConqueredLandButAreIgnoringTheBlock(
        algo,
        currentTraversalIndex
      );
      moveToTheNextBlock(algo);
      return;
    }

    if (whatsAtThisLocation(currentTraversalIndex) == "land") {
      addBlockToFrontier(algo, currentTraversalIndex);
      currentMode[algo] = "conquer_land";
    } else {
      // This is not land, so lets move to the next
      // block in order to find land
      visuallyShowThatCurrentWaterBlockIsExplored(algo);
      moveToTheNextBlock(algo);
    }
  } else {
    conquerLand(algo);
  }
};

document.getElementById("nextButton").addEventListener("click", () => {
  goNext("dfs");
  goNext("bfs");
});

let autoPlayIntervalId = undefined;

document.getElementById("playButton").addEventListener("click", () => {
  autoPlayIntervalId = setInterval(() => {
    goNext("dfs");
    goNext("bfs");
  }, 100);
});

              
            
!
999px

Console