岛屿的数量。题意是给一个二维矩阵,由0和1组成,1代表岛屿。请输出岛屿的数量。例子,
Example 1:
Input: 11110 11010 11000 00000 Output: 1Example 2:
Input: 11000 11000 00100 00011 Output: 3
题意很直观,做法也很直观,分别是DFS和BFS。都是先序遍历的思路,我就直接给代码了。唯一需要解释的地方是BFS的做法,我将坐标变成了code,这样方便记录。DFS的做法更好记。
DFS
时间O(mn)
空间O(mn) - worse case where it's all 0 in the input
1 /** 2 * @param {character[][]} grid 3 * @return {number} 4 */ 5 var numIslands = function (grid) { 6 let res = 0; 7 let m = grid.length; 8 if (m === 0) return 0; 9 let n = grid[0].length; 10 11 var dfs = function (grid, i, j) { 12 if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] === '0') return; 13 grid[i][j] = '0'; 14 dfs(grid, i, j + 1); 15 dfs(grid, i, j - 1); 16 dfs(grid, i - 1, j); 17 dfs(grid, i + 1, j); 18 } 19 20 for (let i = 0; i < m; i++) { 21 for (let j = 0; j < n; j++) { 22 if (grid[i][j] === '1') { 23 dfs(grid, i, j); 24 res++; 25 } 26 } 27 } 28 return res; 29 };
BFS
时间O(mn)
空间O(mn)
1 /** 2 * @param {character[][]} grid 3 * @return {number} 4 */ 5 var numIslands = function (grid) { 6 let res = 0; 7 8 var bfs = function (grid, x, y) { 9 grid[x][y] = '0'; 10 let n = grid.length; 11 let m = grid[0].length; 12 let queue = []; 13 let code = x * m + y; 14 queue.push(code); 15 while (queue.length) { 16 code = queue.shift(); 17 let i = parseInt(code / m); 18 let j = code % m; 19 if (i > 0 && grid[i - 1][j] == '1') { 20 queue.push((i - 1) * m + j); 21 grid[i - 1][j] = '0'; 22 } 23 if (i < n - 1 && grid[i + 1][j] == '1') { 24 queue.push((i + 1) * m + j); 25 grid[i + 1][j] = '0'; 26 } 27 if (j > 0 && grid[i][j - 1] == '1') { 28 queue.push((i * m) + j - 1); 29 grid[i][j - 1] = '0'; 30 } 31 if (j < m - 1 && grid[i][j + 1] == '1') { 32 queue.push((i * m) + j + 1); 33 grid[i][j + 1] = '0'; 34 } 35 } 36 } 37 38 for (let i = 0; i < grid.length; i++) { 39 for (let j = 0; j < grid[0].length; j++) { 40 if (grid[i][j] === '1') { 41 bfs(grid, i, j); 42 res++; 43 } 44 } 45 } 46 return res; 47 };