695. Max Area of Island的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/81134804

我的思路是利用队列存储一块完整的陆地,只要队列不为空就说明在此基础上还可以向四个方向扩展。但是要注意一旦进入队列的点要在原地图上修改成水域,避免重复计算。

class Solution {
public:
	int maxAreaOfIsland(vector<vector<int>>& grid) {
		int result = 0;
		int m = grid.size();
		int n = grid[0].size();
		queue <pair<int, int>> record;
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
			{
				if (grid[i][j])
				{
					int sum = 0;
					record.push(make_pair(i,j));
					grid[i][j] = 0;
					while (!record.empty())
					{
						int x=record.front().first;
						int y =record.front().second;
						if ((x - 1 >= 0) && (grid[x - 1][y])) { record.push(make_pair(x - 1, y)); grid[x - 1][y] = 0; }
						if ((x + 1 < m) && (grid[x + 1][y])) { record.push(make_pair(x + 1, y)); grid[x + 1][y] = 0; }
						if ((y - 1 >= 0) && (grid[x][y - 1])) { record.push(make_pair(x, y - 1)); grid[x][y - 1] = 0; }
						if ((y + 1 < n) && (grid[x][y + 1])) { record.push(make_pair(x, y + 1)); grid[x][y + 1] = 0; }
						record.pop();
						sum++;
					}
					if (sum > result) result = sum;
				}
			}
		return result;
	}
};

还看到一个递归思路的解法,就是当前像素所在的最大陆地面积,等于1(自己的面积)+周围像素点所在陆地的最大面积,注意递归之前也要把当前像素点赋值为水域避免重复计算。

试了几个类似的递归算法发现差距很大,有比我的速度快的也有慢的,不知道为什么。

  int maxAreaOfIsland(vector<vector<int>>& grid) {
        int max_area = 0;
        for(int i = 0; i < grid.size(); i++)
            for(int j = 0; j < grid[0].size(); j++)
                if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j));
        return max_area;
    }
    
    int AreaOfIsland(vector<vector<int>>& grid, int i, int j){
        if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){
            grid[i][j] = 0;
            return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1);
        }
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/81134804
今日推荐