• [LeetCode][JavaScript]Number of Islands


    Number of Islands

    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:

    11110
    11010
    11000
    00000

    Answer: 1

    Example 2:

    11000
    11000
    00100
    00011

    Answer: 3

    https://leetcode.com/problems/number-of-islands/


    广度优先搜索。

    从1开始找所有相连的1,访问过的标记成2,避免重复访问。

    每做一轮计数+1,输出计数结果。

     1 /**
     2  * @param {character[][]} grid
     3  * @return {number}
     4  */
     5 var numIslands = function(grid) {
     6     var x, y, count = 0, m = grid.length, n;
     7     for(x = 0; x < m; x++){
     8         n = grid[0].length;
     9         for(y = 0; y < n; y++){
    10             if(grid[x][y] === '1'){
    11                 bfs([{row : x, col : y}]);
    12                 count++;
    13             }
    14         }
    15     }
    16     return count;
    17 
    18     function bfs(queue){
    19         var len = queue.length, top, split, i, j;
    20         while(len--){
    21             top = queue.pop();        
    22             i = top.row; j = top.col;
    23             if(grid[i] && grid[i][j] && grid[i][j] === '1'){
    24                 grid[i][j] = '2';
    25                 queue.push({row : i + 1, col : j});
    26                 queue.push({row : i - 1, col : j});
    27                 queue.push({row : i, col : j + 1});
    28                 queue.push({row : i, col : j - 1});
    29             }
    30         }
    31         if(queue.length !== 0){
    32             bfs(queue);
    33         }
    34     }
    35 };
  • 相关阅读:
    SSM框架的基本配置
    Python开发的飞机打外星人小游戏
    python中count和index
    破解Xmind时长
    光流法简介
    Linux常用命令
    GitHub常用命令
    极大似然估计与最大后验概率估计
    在linux上加速git clone
    Endnote导入共享数据
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4693445.html
Copyright © 2020-2023  润新知