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 class="row">

  <div class="col">
    <h3>DFS (Blocks covered: <span id="number_of_blocks_covered_dfs">0</span>)</h3>
    <div id="world_canvas_dfs">
    </div>
  </div>
  <div class="col">
    <h3>BFS (Blocks covered: <span id="number_of_blocks_covered_bfs">0</span>)</h3>
    <div id="world_canvas_bfs">
    </div>
  </div>
</div>
<div class="row">
  <div class="col">
    <button class="button-30" role="button" id="playButton">Play</button>
    &nbsp;
    <button class="button-30" role="button" id="nextButton">Next</button>
  </div>
</div>

<script>
  let blockSize = 20
  let worldSize = 20
  let landColor = '#8b624c'
  let waterColor = '#7ee0e0'
  let blockBeingPushedIntoFrontierColor = '#FFFD37'
  let blockToIgnoreColor = '#baadad'
  let conqueredLandColor = '#50C878'
</script>
              
            
!

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 intervalId = undefined;
let bfsComplete = false;
let dfsComplete = false;
let numberOfBlocksCovered = {
    bfs: 0,
    dfs: 0
}

let dfsStack = [
    {
        subArrayIdx: 0,
        subArrayElementIdx: 0,
    }
]

let bfsQueue = [
    {
        subArrayIdx: 0,
        subArrayElementIdx: 0,
    }
]

let dfsHandledObject = {}
let bfsHandledObject = {}

const addBlockToHandledList = (algoType, objWithIdexes) => {
    if (algoType == 'bfs') {
        bfsHandledObject[`${objWithIdexes.subArrayIdx}-${objWithIdexes.subArrayElementIdx}`] = true;
    } else {
        dfsHandledObject[`${objWithIdexes.subArrayIdx}-${objWithIdexes.subArrayElementIdx}`] = true;
    }
}

addBlockToHandledList('bfs', bfsQueue[0]);
addBlockToHandledList('dfs', dfsStack[0]);

const addBlockToFrontier = (algoType, objWithIdexes) => {
    if (algoType == 'bfs') {
        bfsQueue.push(objWithIdexes)
    } else {
        dfsStack.push(objWithIdexes)
    }
}

const hasThisBlockBeenHandled = (algoType, objWithIdexes) => {
    let val;
    if (algoType == 'bfs') {
        val = bfsHandledObject[`${objWithIdexes.subArrayIdx}-${objWithIdexes.subArrayElementIdx}`];
    } else {
        val = dfsHandledObject[`${objWithIdexes.subArrayIdx}-${objWithIdexes.subArrayElementIdx}`];
    }
    if (val == undefined) {
        return false
    } else {
        val;
    }
}

const doesBlockExist = ({ subArrayIdx, subArrayElementIdx }) => {
    // Check if the idxs are too low
    if (subArrayIdx < 0 || subArrayElementIdx < 0) {
        return false;
    }
    let maxIndexPossibleForBothIndexes = worldSize - 1;
    // Check if the idxes are too high
    if (subArrayIdx > maxIndexPossibleForBothIndexes || subArrayElementIdx > maxIndexPossibleForBothIndexes) {
        return false;
    }
    return true;
}

const addNeighborsToQueue = (algo, subArrayIdx, subArrayElementIdx) => {
    let blockAbove = {
        subArrayIdx: subArrayIdx - 1,
        subArrayElementIdx: subArrayElementIdx
    }

    let blockBelow = {
        subArrayIdx: subArrayIdx + 1,
        subArrayElementIdx: subArrayElementIdx
    }

    let blockOnTheRight = {
        subArrayIdx: subArrayIdx,
        subArrayElementIdx: subArrayElementIdx + 1
    }

    let blockOnTheLeft = {
        subArrayIdx: subArrayIdx,
        subArrayElementIdx: subArrayElementIdx - 1
    }

    let allSurroundingBlocks = [
        blockAbove, blockBelow, blockOnTheRight, blockOnTheLeft
    ]

    allSurroundingBlocks.forEach((blockObject) => {
        if (doesBlockExist(blockObject) && hasThisBlockBeenHandled(algo, blockObject) == false) {
            changeBlockColorAndReDrawWorld(algo, blockObject.subArrayIdx, blockObject.subArrayElementIdx, blockBeingPushedIntoFrontierColor);
            addBlockToHandledList(algo, blockObject);
            addBlockToFrontier(algo, blockObject);
        }
    })
}

const closeAnimationIfDFSAndBFSAreComplete = () => {
    if ( bfsComplete && dfsComplete ) {
        console.log('Both are complete to stopping animation.')
        clearInterval(intervalId);
    }
}

const incrementBlockAndUpdateBlockCount = (algo) => {
    numberOfBlocksCovered[algo] += 1;
    let selectorForCounterInUI = `number_of_blocks_covered_${algo}`;
    document.getElementById(selectorForCounterInUI).innerText = numberOfBlocksCovered[algo];
}

const processNextStepInBFS = () => {

    let elementToProcess = bfsQueue.shift();
    if (elementToProcess == undefined) {
        bfsComplete = true;
        closeAnimationIfDFSAndBFSAreComplete();
        return;
    }

    changeBlockColorAndReDrawWorld('bfs', elementToProcess.subArrayIdx, elementToProcess.subArrayElementIdx, conqueredLandColor);
    incrementBlockAndUpdateBlockCount('bfs');

    addNeighborsToQueue('bfs', elementToProcess.subArrayIdx, elementToProcess.subArrayElementIdx);
}

const processNextStepInDFS = () => {

    let elementToProcess = dfsStack.pop();
    if (elementToProcess == undefined) {
        dfsComplete = true;
        closeAnimationIfDFSAndBFSAreComplete();
        return;
    }

    changeBlockColorAndReDrawWorld('dfs', elementToProcess.subArrayIdx, elementToProcess.subArrayElementIdx, conqueredLandColor);
    incrementBlockAndUpdateBlockCount('dfs');

    addNeighborsToQueue('dfs', elementToProcess.subArrayIdx, elementToProcess.subArrayElementIdx);
}

const processNextStepsInAlgo = () => {
    console.log('New step');
    processNextStepInBFS()
    processNextStepInDFS()
}

document.getElementById("nextButton").addEventListener("click", () => {
    processNextStepsInAlgo();
})

document.getElementById('playButton').addEventListener('click', () => {
    if (intervalId) {
        return;
    }
    intervalId = setInterval(processNextStepsInAlgo, 10);
})

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

    world.forEach((latitudeRow, latitudeIdx) => {
        let blockRow = []
        latitudeRow.forEach((longitudeCell, longitudeIdx) => {
            let x = longitudeIdx * blockSize
            let y = latitudeIdx * blockSize
            let color = longitudeCell === 0 ? waterColor : landColor
            blockRow.push({ x, y, color })
        });
        blockSettingsArray.push(blockRow)
    })
    return blockSettingsArray;
}

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

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

const changeBlockColorAndReDrawWorld = (whichWorld, latitudeIdx, longitudeIdx, newColor) => {
    let worldAsBlockSettings = undefined;
    let idOfElement = undefined;
    if (whichWorld == "bfs") {
        worldAsBlockSettings = bfsWorldAsBlockSettings;
        idOfElement = "world_canvas_bfs";
    } else {
        worldAsBlockSettings = dfsWorldAsBlockSettings;
        idOfElement = "world_canvas_dfs";
    }
    worldAsBlockSettings[latitudeIdx][longitudeIdx].color = newColor;
    drawWorld(worldAsBlockSettings, idOfElement)
}

let bfsWorld = generateWorld(worldSize, worldSize)
let dfsWorld = generateWorld(worldSize, worldSize)

let bfsWorldAsBlockSettings = convertWorldToBlockSettingsArray(bfsWorld)
let dfsWorldAsBlockSettings = convertWorldToBlockSettingsArray(dfsWorld)

drawWorld(bfsWorldAsBlockSettings, 'world_canvas_bfs')
drawWorld(dfsWorldAsBlockSettings, 'world_canvas_dfs')
              
            
!
999px

Console