本文主要是介绍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.
示例:
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);}
};
这篇关于Number of Islands问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!