链接
https://leetcode.com/problems/max-area-of-island/
leetcode(695): Max Area of Island

题目

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

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.

思路

题目给了我们一个 2d grid array, 让我们找到所有岛中区域最大的一个,返回区域值。0代表海洋,1代表陆地。陆地与陆地相连,只能是横向和纵向,不可以斜着。

因为只能横向和纵向相连,所以每一个cell 只能是4个方向延伸,左 上 右 下。

这道题目要用到Depth-first Search,遍历2d array,遇到1的时候,就利用dfs把这个岛的区域大小找全。我的dps顺序是 左,上,右,下。在递归dfs之前,要把目前的cell

设为0,是为了避免dfs又往回走,每一个数过的cell,就不需要在重复走了。

代码


		class Solution {
		public:

			void change(vector<vector<int>>& grid, int i, int j,int &count) {

				if (i < 0 || i >= grid.size() || j<0 || j>=grid[0].size())
					return;
				if (grid[i][j] == 0)  return;
				if (grid[i][j] == 1) {
					grid[i][j] = 0;
					count++;
					change(grid, i - 1, j, count);
					change(grid, i, j - 1,count);
					change(grid, i + 1, j,count);
					change(grid, i, j + 1,count);
				}
			}

			int maxAreaOfIsland(vector<vector<int>>& grid) {
				int n = grid.size();
				if (n == 0)
					return 0;
				int m = grid[0].size();
				int maxArea = 0;
				int count = 0;
				for (int i = 0; i < n; i++) {
					for (int j = 0; j < m; j++) {
						if (grid[i][j] == 1) {
							
							change(grid, i, j, count);
							maxArea = max(count, maxArea);
							count = 0;
						}

					}


				}

				return maxArea;
			}
		};


相关文章: