Leetcode岛屿问题

463. 岛屿的周长

  • 每有一个位置是1,则周长+4
  • 如果上一个是1,则公用上边,周长-2;如果左一个是1,则公用左边,周长-2
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int n = grid.size();
        if(n==0) return 0;
        int m = grid[0].size();
        int sum = 0;
        for(int i=0; i<n; ++i){
            for(int j=0; j<m; ++j){
                if(grid[i][j] == 1){
                    sum += 4;
                    //上
                    if(i>0 && grid[i-1][j]==1){
                        sum -= 2;
                    }
                    //左
                    if(j>0 && grid[i][j-1]==1){
                        sum -= 2;
                    }
                } 
            }
        }
        return sum;
    }
};

695. 岛屿的最大面积

  • 先找起点,也就是grid[i][j]==1
  • 从起点开始dfs, 上下左右四个方向,每有一个方向上grid[i][j]==1,则岛屿面积+1
  • 为防止重复遍历,需要记录访问过的地方。方法一:原地修改数组,访问过的地方置0; 方法二:额外数组标记访问过的状态
class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        n = grid.size();
        if(n==0) return 0;
        m = grid[0].size();

        vector<vector<bool>> visited(n, vector<bool>(m,0));
        for(int i=0; i<n; ++i){
            for(int j=0; j<m; ++j){
                if(!visited[i][j] && grid[i][j]==1){
                    maxArea = max(maxArea, dfs(grid, visited, i, j));
                }
            }
        }
        return maxArea;
    }
    int dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int row, int col){
        if(row<0 || row>=n || col<0 || col>=m || grid[row][col] == 0) return 0;
        //
        //cout << row << "," << col << "=" << grid[row][col] << "\n";
        int cnt = 0;
        if(!visited[row][col]){
            cnt = 1;
            visited[row][col] = true;
            cnt += dfs(grid, visited, row-1, col);
            cnt += dfs(grid, visited, row+1, col);
            cnt += dfs(grid, visited, row, col-1);
            cnt += dfs(grid, visited, row, col+1);
        }
        return cnt;
    }
private:
    int maxArea = 0;
    int n, m;
};
posted @ 2020-10-30 11:16  miyanyan  阅读(155)  评论(0编辑  收藏  举报