问题:
给定一个由0,1 组成的二维数组,0代表海水,1代表陆地,
求给定数组所形成小岛的最大面积。
Example 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. Example 2: [[0,0,0,0,0,0,0,0]] Given the above grid, return 0. Note: The length of each dimension in the given grid does not exceed 50.
解法:DFS
深度优先递归
标记已遍历过为0: grid[i][j]=0;
向四个方向逐次探索,若不满足条件:超出数组范围or为海水节点0,则直接返回当前面积为0
否则当前面积为1,在以当前节点为轴心,再次向四周探索。每个方向的结果累加,最后返回总面积。
在最外层,顺次遍历整个给定数组,只对 未曾访问过&&陆地节点(grid[i][j]=1)的节点进行上述递归处理。
代码参考:
1 class Solution { 2 public: 3 int dfs(vector<vector<int>>& grid, int n, int m, int i, int j){ 4 if(i<0 || i>=n || j<0 || j>=m || grid[i][j] == 0) return 0; 5 grid[i][j]=0; 6 int area=1; 7 area+=dfs(grid, n, m, i-1, j); 8 area+=dfs(grid, n, m, i+1, j); 9 area+=dfs(grid, n, m, i, j-1); 10 area+=dfs(grid, n, m, i, j+1); 11 return area; 12 } 13 int maxAreaOfIsland(vector<vector<int>>& grid) { 14 int res=0; 15 if(grid.size()==0)return 0; 16 int n=grid.size(), m=grid[0].size(); 17 for(int i=0; i<n; i++){ 18 for(int j=0; j<m; j++){ 19 if(grid[i][j]==1){ 20 res=max(res,dfs(grid, n, m, i, j)); 21 } 22 } 23 } 24 return res; 25 } 26 };