Clarifying logic on Minesweeper algorithm

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

When asking for programming help for non-FCC curriculum challenges or projects, can you please use the Programming Help category in the future? I have changed it for you this time. Thank you.

1 Like

Your understanding is generally correct. There are couple adjustments and improvement could be made however:

  1. You don’t have to write === true in the if condition that already expects true, you can just:
if (matrix[i - 1][j])

*like you actually did in the last 2 if statements
2. Considering number of cells always greater than number of mines, it would be way more efficient to increment cells around if you found a mine, rather than counting mines around every cell