JSFiddle - React, Tailwind, and code Playground
CSS
html,body {
font-family: monospace;
}
JavaScript
document.body.innerHTML=process("\
.#####....\n\
.#....####\n\
###.###..#\n\
#.#...##..\n\
.####..#.#\n\
......###.\n\
..#...#..#\n\
..#...#..#").replace(/\n/g,"<br/>");
// begin code
function process(input){
function replaceAt(s, index, character) {
return s.substr(0, index) + character +
s.substr(index+1);
}
input = input.split("\n");
w = input[0].length;
h = input.length;
function getR(x, y){ return input[y][x] == "#"; }
function getF(x, y){ return input[y][x] == "F"; }
function set(x, y, c){ input[y] = replaceAt(input[y], x, c); }
function floodFill(x, y){
if(!getR(x,y))return;
set(x, y, "F");
if(x>1)floodFill(x-1,y);
if(x<w-1)floodFill(x+1,y);
if(y>1)floodFill(x, y-1);
if(y<h-1)floodFill(x, y+1);
}
for(i=0;i<w;i++){
if(getR(i, h-1)){
floodFill(i, h-1);
}
}
for(j=h-2;j>-1;j--){
for(i=0;i<w;i++){
k = j+1;
if(getR(i, j)){
while(k<h&&(!getF(i,k))&&(!getR(i,k)))k++;
k--;
set(i, j, ".");
set(i,k,"#");
}
}
}
return input.join("\n").replace(/F/g,"#");
}