Number of Islands问题及解法

来源:互联网 发布:伯明翰 知乎 编辑:程序博客网 时间:2024/05/18 18:43

问题描述:

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.

示例:

11110
11010
11000
00000

Answer: 1

11000
11000
00100
00011

Answer: 3

问题分析:

分析题意可知,我们只需要把’1‘的连通区域的个数求解出来即可,这里采用深度优先遍历求解。


过程详见代码:

class Solution {public:    int numIslands(vector<vector<char>>& grid) {int m = grid.size();        if(!m) return 0;int n = grid[0].size();int count = 2;for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (grid[i][j] == '1'){bl(grid, count, i, j, m, n);count++;}}}return count - 2;}void bl(vector<vector<char>>& grid, int count, int i, int j, int m, int n){grid[i][j] = (char)('0' + count);if (j + 1 < n && grid[i][j + 1] == '1') bl(grid, count, i, j + 1, m, n);if (i + 1 < m && grid[i + 1][j] == '1') bl(grid, count, i + 1, j, m, n);if (j - 1 >= 0 && grid[i][j - 1] == '1') bl(grid, count, i, j - 1, m, n);if (i - 1 >= 0 && grid[i - 1][j] == '1') bl(grid, count, i - 1, j, m, n);}};


原创粉丝点击