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:
11110110101100000000
Answer: 1
Example 2:
11000110000010000011
Answer: 3
计算孤岛的数量,注意上下左右为0就是孤岛,孤岛可以很大,grid范围以外的都算是water。代码如下所示:
1 class Solution { 2 public: 3 int numIslands(vector<vector<char>>& grid) { 4 int count = 0; 5 if(!grid.size() || !grid[0].size()) 6 return count; 7 int row = grid.size(); 8 int col = grid[0].size(); 9 for(int i = 0; i < row; ++i){ 10 for(int j = 0; j < col; ++j){ 11 if(grid[i][j] == ‘1‘){ 12 dfs(grid, i, j); 13 count++; 14 } 15 16 } 17 } 18 return count; 19 } 20 21 void dfs(vector<vector<char>> & grid, int x, int y) 22 { 23 if(grid[x][y] == ‘1‘) 24 grid[x][y] = ‘X‘; 25 else 26 return; 27 dfs(grid, x+1, y); 28 dfs(grid, x-1, y); 29 dfs(grid, x, y+1); 30 dfs(grid, x, y0); 31 } 32 };
时间: 2024-10-14 05:18:00