HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
<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>
<button class="button-30" role="button" id="nextButton">Next</button>
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;
}
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);
});
Also see: Tab Triggers