Home > Software engineering >  2D Array Bug in JS
2D Array Bug in JS

Time:11-27

I have an identical copy of a 2D array that returns reading property of undefined, but the original does not. Does anyone know why that is? I've attached my code. I think it maybe has to do with how I copied the array, but when I console.log them, they return the same thing, except one is filled with false and the other is filled with string numbers.

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
  let MAX_X = grid.length;
  let MAX_Y = grid[0].length;
  let num_of_islands = 0;
  const visited = grid.map((row) => {
      return (
          row.map((square) => {
              return (
                  false
              )
          })
      )
  })
   console.log(grid);
   console.log(visited);

  for(let x = 0; x < MAX_X; x  ) {
      for(let y = 0; y < MAX_Y; y  ) {
          if(grid[x][y] === '1' && !visited[x][y]) {
              num_of_islands = 1;
              DFS(grid, x, y, visited)
          }
      }
  } 
   return num_of_islands
};

function DFS(grid, x, y, visited) {
   if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
       return;
   }
   if(grid[x][y] === '0' || visited[x][y]) {
       return;
   }
   
   grid[x][y] = '0';
   visited[x][y] = true;
   DFS(grid, x   1, y);
   DFS(grid, x - 1, y); 
   DFS(grid, x, y   1);
   DFS(grid, x, y - 1);
}
let grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]];

console.log(numIslands(grid));

CodePudding user response:

The error you got "reading property of undefined" has nothing to do with the way you copy an array, but with a function parameter for which you have not provided an argument.

The recursive calls only pass 3 arguments, while 4 are expected. So change this:

   DFS(grid, x   1, y);
   DFS(grid, x - 1, y); 
   DFS(grid, x, y   1);
   DFS(grid, x, y - 1);

By:

   DFS(grid, x   1, y, visited);
   DFS(grid, x - 1, y, visited); 
   DFS(grid, x, y   1, visited);
   DFS(grid, x, y - 1, visited);
  • Related