Given consisting of '1'
(land), and '0'
(water) consisting of two-dimensional grid, the number of islands of computing. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.
Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
Solution (C ++):
class Solution { public: //广度优先搜索 void dfs(vector<vector<char>>& grid, int x, int y) { int nx = grid.size(); int ny = grid[0].size(); grid[x][y] = '0'; if (x-1>=0 && grid[x-1][y] == '1') dfs(grid, x-1, y); if (x+1<nx && grid[x+1][y] == '1') dfs(grid, x+1, y); if (y-1>=0 && grid[x][y-1] == '1') dfs(grid, x, y-1); if (y+1<ny && grid[x][y+1] == '1') dfs(grid, x, y+1); } int numIslands(vector<vector<char>>& grid) { int island = 0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if (grid[i][j] == '1') { ++island; dfs(grid, i, j); } } } return island; } };