標籤:
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