码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Number of Islands

时间:2015-08-01 00:58:34      阅读:743      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

[LeetCode][JavaScript]Number of Islands

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!