[leetcode 200] 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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Solution:

dfs遍历一遍,在grid[i][j]如果是1,就把这个位置和周围置成2(任意非1和0的值), 这样遇到的1的个数,即为islands个数

 1 void dfs(char** grid, int m, int n, int i, int j)
 2 {
 3     if (i < 0 || i >= m || j < 0 || j >= n)
 4         return;
 5     if (grid[i][j] == '1')
 6     {
 7         grid[i][j] = '2';
 8         dfs(grid, m, n, i - 1, j);
 9         dfs(grid, m, n, i + 1, j);
10         dfs(grid, m, n, i, j - 1);
11         dfs(grid, m, n, i, j + 1);
12     }
13 }
14 
15 int numIslands(char** grid, int gridRowSize, int gridColSize) 
16 {
17     int count = 0;
18     int i = 0, j = 0;
19     if (gridRowSize == 0 || gridColSize == 0 || grid == NULL)
20         return count;
21     
22     for (i = 0; i < gridRowSize; i++)
23     {
24         for (j = 0; j < gridColSize; j++)
25         {
26             if (grid[i][j] != '1')
27             {
28                 continue;
29             }
30             count++;
31             dfs(grid, gridRowSize, gridColSize, i, j);
32         }
33     }
34     
35     return count;
36 }

 

你可能感兴趣的:([leetcode 200] Number of Islands)