Guest User

Untitled

a guest
Mar 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. /*
  2. Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
  3.  
  4. Example 1:
  5.  
  6. 11110
  7. 11010
  8. 11000
  9. 00000
  10. Answer: 1
  11.  
  12. Example 2:
  13.  
  14. 11000
  15. 11000
  16. 00100
  17. 00011
  18. Answer: 3
  19. */
  20.  
  21. /**
  22. * @param {character[][]} grid
  23. * @return {number}
  24. */
  25. var numIslands = function(grid) {
  26. var arr = grid;
  27. var count = 0;
  28. for(var x = 0; x < arr.length; x++) {
  29. for (var y = 0; y < arr[0].length; y++) {
  30. if(arr[x][y] === '1') {
  31. arr[x][y] = '0';
  32. count++;
  33. helper(arr, x + 1, y);
  34. helper(arr, x, y + 1);
  35. helper(arr, x - 1, y);
  36. helper(arr, x, y -1 );
  37. }
  38. }
  39. }
  40. return count;
  41. };
  42.  
  43. function helper(arr, x, y) {
  44. if(x > arr.length - 1 || y > arr[0].length - 1) {
  45. return;
  46. }
  47. if(x < 0 || y < 0) {
  48. return;
  49. }
  50. if(arr[x][y] === '0' ) {
  51. return;
  52. }
  53. if(arr[x][y] === '1') {
  54. arr[x][y] = '0';
  55. }
  56. helper(arr, x + 1, y);
  57. helper(arr, x, y + 1);
  58. helper(arr, x - 1, y);
  59. helper(arr, x, y -1 );
  60. }
Add Comment
Please, Sign In to add comment