I am working on a minesweeper algorithm and I want to make sure that how I’m understanding it is correct. I’ve got my code below and if anyone could look over the logic and correct any misunderstandings I would appreciate it.
function minesweeper(matrix: boolean[][]): number[][] {
//instantiate an array
let mineSwept:any[] = [];
for(let i = 0; i < matrix.length; ++i){
/*push array into this array, then it will be double nested and
you will start in the middle of the 3X3 matrix*/
mineSwept.push([]);
for(let j = 0; j < matrix[i].length; ++j){
let count = 0;
//i is greater than 0 so that you don't start on an edge
if(i>0){
//left
if(matrix[i-1][j]===true){
count+=1;
}
//upper left
if(matrix[i-1][j-1]===true){
count+=1;
}
//lower left
if(matrix[i-1][j+1]===true){
count+=1;
}
}
//moving across the array to just before the end to avoid edges
if(i < matrix[i].length-1){
//right
if(matrix[i+1][j]===true){
count+=1;
}
//top right
if(matrix[i+1][j+1]===true){
count+=1
}
//down right
if(matrix[i+1][j-1]===true){
count+=1
}
}
//top middle
if(matrix[i][j+1]){
count+=1;
}
//bottom middle
if(matrix[i][j-1]){
count+=1
}
/*count has been aggregating all possible cell values as it moves
the .push of count to mineSwept[i] places those values into their
respective containers*/
mineSwept[i].push(count)
}
console.log(mineSwept)
}
return mineSwept