[LeetCode][JavaScript]Number of Islands

时间:2015-08-01 00:55:54   收藏:0   阅读:274

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 };

 

 

原文:http://www.cnblogs.com/Liok3187/p/4693445.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!