JSFiddle - React, Tailwind, and code Playground
HTML
<pre class=B id=P0></pre>
<pre class=B id=P1></pre>
<pre class=B id=P2></pre>
<pre class=B id=P3></pre>
<pre class=B id=P4></pre>
<br>
Select a puzzle or enter your own
<button id=BGO title='Find a solution'>Go</button>
<button id=BC>Clear</button>
<button id=BA>Animate</button>
<div id=INFO></div><div id=SOL></div>
<textarea id=TB></textarea>
<textarea id=AB></textarea>
CSS
body {
font-family: helvetica;
}
pre.B {
font-size:12px;
display:inline-block;
border: 1px solid #888;
}
textarea {
width: 100px;
height: 200px;
}
#SOL,#INFO {
font-size: 12px;
}
#SOL b {
color:red;
}
}
JavaScript
Pz={P0:'#######\n#001gg#\n##.222#\n.######',
P1:'..####..\n..#00#..\n###00###\n#......#\n#.1122.#\n##3124##\n.#3344#.\n.##55##.\n..#gg#..\n..####..',
P2:'######\n#1002#\n#1002#\n#3445#\n#3675#\n#8gg9#\n######',
P3:'.####.\n##1g##\n#22g3#\n#4255#\n#4.56#\n#.006#\n#7008#\n######',
P4:'.####.\n##00##\n#.00g#\n#.0.1#\n#..g2#\n######'};
for(p in Pz) $('#'+p).text(Pz[p]);
$('pre.B').on('click', function(){ $("#TA").val(''),$("#TB").val($(this).text()) })
$('#BC').on('click', _=>($("#TB,#AB").val(''),$("#SOL,#INFO").text('')))
$('#BA').on('click',_=>Anim($('#TB').val(),$('#SOL').text()));
$('#BGO').on('click',
function() {
x=$("#TB").val();
n=x.search(/\n/)
err=''
$("#SOL").text('')
$("#AB").val('')
if ((v=x.replace(/[\d.g#\n]/g,''))!='') err='Unexpected characters: ' +v
else if (x.search(/g/)<0) err='missing goal'
else if (x.split(/\n/).some(r=>r.length!=n)) err='each row must be same length'
if (err) $("#INFO").text(x+'\n\nInvalid: '+err);
else {
$("#INFO").text('... running ...');
setTimeout(function(){
var T=~new Date,v,h
v=F(x)
if ($('#CBA').prop('checked')) Anim(x,v)
T-=~new Date
$("#INFO").text('T(ms) '+T+' Len:' + v.length/3);
$("#SOL").html(v)
},100)
}
})
Anim=_=>{
var i=0,g=$('#TB').val(), s=$('#SOL').text().match(/\w\w/g), o=~g.search(/\n/);
$("#AB").val(g);
g=[...g];
var A=_=>{
var x,b,d,m
if(x=s[i]){
$('#SOL').html(s.map((v,p)=>p==i?'<b>'+v+'</b>':v).join(' '))
++i
b=x[0],d=x[1]
d=[-1,1,o,-o]['LRUD'.search(d)]
m=[...g]
g.forEach((c,p)=>c==b?m[g[p-d]!=b?m[p]='.':0,p+d]=b:0)
g=m
$("#AB").val(g.join(''))
setTimeout(A,500)
}
}
A()
}
F=g=>(o=>{
for(u=[i=s=''],v={},h=[],b={},k={'.':-1},l={},
g=[...g].map((c,p)=>c=='g'?(h.push(p),'.'):c<'0'?c:
l[k[c]?k[c]+=','+(p-b[c]):k[b[c]=p,c]=~(c>0),k[c]]=c),
...