【LeetCode with JavaScript】 200. Number of Islands

客官°小女子只卖身不卖艺 2022-05-24 08:42 274阅读 0赞

原题网址:https://leetcode.com/problems/number-of-islands
难度:Medium

题目

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.

Example 1:

  1. Input:
  2. 11110
  3. 11010
  4. 11000
  5. 00000
  6. Output: 1

Example 2:

  1. Input:
  2. 11000
  3. 11000
  4. 00100
  5. 00011
  6. Output: 3

思路


这是一道找岛屿数量的题目,”1”代表陆地,”0”代表海洋。

  1. 首先定义一个函数 clearIsland(x, y, grid),函数功能输入一个 (x, y) 坐标,将该点连着的陆地 “1”,全部清理为 “0”,实现思路类似二叉树的深度优先遍历(Depth-First Traversa),对该点的上下左右方向依次进行递归查找,当超出边界或抵达海洋,则结束单次递归;
  2. 对 Input 的二维数组进行遍历,对每个 “1”,调用一次 clearIsland,清空该点连着的陆地,并使岛屿数量加一。

实现代码如下:

  1. /**
  2. * @param {character[][]} grid
  3. * @return {number}
  4. */
  5. var numIslands = function(grid) {
  6. var num = 0;
  7. for(var i = 0; i < grid.length; i++) {
  8. for(var j = 0; j < grid[0].length; j++) {
  9. if(grid[i][j] === "1") {
  10. findIsland(i, j, grid);
  11. num ++;
  12. }
  13. }
  14. }
  15. return num;
  16. }
  17. function findIsland(x, y, grid) {
  18. if(x < 0 || y < 0
  19. || x > grid.length - 1 || y > grid[x].length - 1
  20. || grid[x][y] === "0")
  21. return;
  22. grid[x][y] = "0";
  23. findIsland(x - 1, y, grid);
  24. findIsland(x, y - 1, grid);
  25. findIsland(x + 1, y, grid);
  26. findIsland(x, y + 1, grid);
  27. }

Your runtime beats 93.88 % of javascript submissions.
运行时间:68ms,clear!

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读