[LeetCode] 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

没什么,DFS就好了。

 1 class Solution {

 2 public:

 3     void dfs(vector<vector<char>> &grid, int x, int y) {

 4         if (x < 0 || x >= grid.size()) return;

 5         if (y < 0 || y >= grid[0].size()) return;

 6         if (grid[x][y] != '1') return;

 7         grid[x][y] = 'X';

 8         dfs(grid, x + 1, y);

 9         dfs(grid, x - 1, y);

10         dfs(grid, x, y + 1);

11         dfs(grid, x, y - 1);

12     }

13     

14     int numIslands(vector<vector<char>> &grid) {

15         if (grid.empty() || grid[0].empty()) return 0;

16         int N = grid.size(), M = grid[0].size();

17         int cnt = 0;

18         for (int i = 0; i < N; ++i) {

19             for (int j = 0; j < M; ++j) {

20                 if (grid[i][j] == '1') {

21                     dfs(grid, i, j);

22                     ++cnt;

23                 }

24             }

25         }

26         return cnt;

27     }

28 };

 

你可能感兴趣的:(LeetCode)