Advertisement
tcool86

Untitled

Nov 13th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var numIslands = function(grid) {
  2.     if (grid.length === 0) { return 0; }
  3.     let count = 0;
  4.    
  5.     function depthSearch(x, y) {
  6.         if (grid[x][y] === '1') {
  7.             grid[x][y] = '0';
  8.         } else {
  9.             return;
  10.         }
  11.  
  12.         if (x < grid.length - 1) {
  13.             depthSearch(x+1, y);
  14.         }
  15.        
  16.         if (y < grid[x].length - 1) {
  17.             depthSearch(x, y+1);
  18.         }
  19.        
  20.         if (x > 0 && x < grid.length) {
  21.             depthSearch(x-1, y);
  22.         }
  23.        
  24.         if (y > 0 && y < grid[x].length) {
  25.             depthSearch(x, y-1);
  26.         }
  27.     }
  28.    
  29.     for (let i = 0; i < grid.length; i++) {
  30.         for (let j = 0; j < grid[i].length; j++) {
  31.             if (grid[i][j] === '1') {
  32.                 count++;
  33.                 depthSearch(i, j);
  34.             }
  35.         }
  36.     }
  37.    
  38.     return count;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement