• Leetcode 1254. Number of Closed Islands


    Leetcode 1254. Number of Closed Islands

    Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

    Return the number of closed islands.

    Example 1:
    img

    Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
    Output: 2
    Explanation:
    Islands in gray are closed because they are completely surrounded by water (group of 1s).
    Example 2:
    img

    Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
    Output: 1
    Example 3:

    Input: grid = [[1,1,1,1,1,1,1],
                   [1,0,0,0,0,0,1],
                   [1,0,1,1,1,0,1],
                   [1,0,1,0,1,0,1],
                   [1,0,1,1,1,0,1],
                   [1,0,0,0,0,0,1],
                   [1,1,1,1,1,1,1]]
    Output: 2
     
    
    Constraints:
    
    1 <= grid.length, grid[0].length <= 100
    0 <= grid[i][j] <=1
    

    solution

    需要找出四周环水的岛屿数量,在边界处的岛屿不能算四周环水,所以先把四周的岛屿变成水,在按照Leetcode 200. Number of Islands的方法处理就好了

    class Solution {
    public:
        int closedIsland(vector<vector<int>>& grid) {
            if (grid.empty())
    			return 0;
    		int n = grid.size();
    		int m = grid[0].size();
            
            for(int i = 0; i < n; i++)
                for(int j = 0; j < m; j++)
                    if(grid[i][j] == 0 && (i == 0 || j == 0 || i == (n-1) || j == (m-1)))
                        DFS(grid, i, j, n, m);
            
    		int ans = 0;
    		for (int i = 0; i < n; i++)
    			for (int j = 0; j < m; j++)
    			{
    				if (grid[i][j] == 0)
    				{
    					ans++;
    					DFS(grid, i, j, n, m);
    				}
    			}
    		return ans;
    
    	}
    	void DFS(vector<vector<int>>& grid, int i, int j, int n, int m)
    	{
    		if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 1)
    			return;
    		grid[i][j] = 1;
    		DFS(grid, i + 1, j, n, m);
    		DFS(grid, i - 1, j, n, m);
    		DFS(grid, i, j + 1, n, m);
    		DFS(grid, i, j - 1, n, m);
    
    	}
        
    };
    

    参考链接

    leetcode
    Leetcode 200. Number of Islands

    blogs record our growth
  • 相关阅读:
    [JSOI2004]平衡点
    [HNOI2009]梦幻布丁
    蒜头君救人
    蒜头君的排序
    蒜头君的坐骑
    [ZJOI2006]超级麻将
    环状最大两段子段和
    洛谷P2480 [SDOI2010]古代猪文(卢卡斯定理+中国剩余定理)
    线性基学习笔记
    洛谷P2473 [SCOI2008]奖励关(期望+状压)
  • 原文地址:https://www.cnblogs.com/qwfand/p/12722592.html
Copyright © 2020-2023  润新知