Worked example and algorithm walkthrough
Topic: Recursion & Backtracking · Constraint search
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
[ "534678912", "672195348", "198342567", "859761423", "426853791", "713924856", "961537284", "287419635", "345286170" ]
Execution steps
- Test digit 1
- Test digit 2
- Test digit 3
- Test digit 4
- Test digit 5
- Test digit 6
- Test digit 7
- Test digit 8
- Test digit 9
Computed output
[ "534678912", "672195348", "198342567", "859761423", "426853791", "713924856", "961537284", "287419635", "345286179" ]
JavaScript reference implementation
const solve = (a,s)=>{
let b=a.map(r=>[...r]);
function f(){
for(let i=0;
i<9;
i++)for(let j=0;
j<9;
j++)if(b[i][j]==="0"){
for(let x of "123456789"){
let ok=!b[i].includes(x)&&b.every(r=>r[j]!==x);
for(let r=Math.floor(i/3)*3;
r<Math.floor(i/3)*3+3;
r++)for(let c=Math.floor(j/3)*3;
c<Math.floor(j/3)*3+3;
c++)if(b[r][c]===x)ok=false;
s("Test digit "+x,{
Grid:b,Cell:[i,j],Candidate:[x],Allowed:[ok]
});
if(ok){
b[i][j]=x;
if(f())return true;
b[i][j]="0"
}
}
return false
}
return true
}
f();
return b.map(r=>r.join(""))
};