LeetCode Number of Islands

原题链接在这里:https://leetcode.com/problems/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

若是碰到一个1, 用DFS把与它相连的1 都换成0. 继续扫描,最后算出能有多少个 单独的 1.

Time Complexity: O(m*n), m = grid.length, n = grid[0].length. 看起来像 O(m^2 * n^2), 对于每一个点 做DFS 用O(m*n). 一共m*n个点。

其实每个点最多扫描两遍。

Space: O(m*n) 最多可以有O(m*n)层 stack. 

AC Java:

 1 public class Solution {
 2     public int numIslands(char[][] grid) {
 3         if(grid == null || grid.length == 0 || grid[0].length == 0){
 4             return 0;
 5         }
 6         int res = 0;
 7         for(int i = 0; i<grid.length; i++){
 8             for(int j = 0; j<grid[0].length; j++){
 9                 if(grid[i][j] == '1'){
10                     res++;
11                     replace(grid,i,j);
12                 }
13             }
14         }
15         return res;
16     }
17     private void replace(char[][] grid, int i, int j){
18         if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] != '1'){
19             return;
20         }
21         grid[i][j] = '0';
22         replace(grid,i-1,j);
23         replace(grid,i+1,j);
24         replace(grid,i,j-1);
25         replace(grid,i,j+1);
26     }
27 }

 跟上Number of Islands II

你可能感兴趣的:(LeetCode Number of Islands)