Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1254.html

1254. Number of Closed Islands (Medium)

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:

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:

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

Related Topics: Depth-first Search

Solution 1. DFS

// OJ: https://leetcode.com/problems/number-of-closed-islands/
// Time: O(MN)
// Space: O(1)
class Solution {
    int dirs[4][2] = { {0,1},{0,-1},{-1,0},{1,0} }, M, N;
    bool dfs(vector<vector<int>> &G, int x, int y, int id) {
        G[x][y] = id;
        bool ans = true;
        for (auto &[dx, dy] : dirs) {
            int a = x + dx, b = y + dy;
            bool oob = a < 0 || b < 0 || a >= M || b >= N;
            ans = ans && !oob;
            if (oob || G[a][b] != 0) continue;
            ans = dfs(G, a, b, id) && ans;
        }
        return ans;
    }
public:
    int closedIsland(vector<vector<int>>& G) {
        int id = 2, ans = 0;
        M = G.size(), N = G[0].size();
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                if (G[i][j] != 0) continue;
                if (dfs(G, i, j, id++)) ++ans;
            }
        }
        return ans;
    }
};
  • class Solution {
        final int WATER = -1;
        final int WHITE = 0;
        final int GRAY = 1;
        final int BLACK = 2;
    
        public int closedIsland(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0)
                return 0;
            int rows = grid.length, columns = grid[0].length;
            int insideRows = rows - 1, insideColumns = columns - 1;
            int[][] colors = new int[rows][columns];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++)
                    colors[i][j] = grid[i][j] == 1 ? WATER : WHITE;
            }
            for (int i = 0; i < rows; i++) {
                if (colors[i][0] == WHITE)
                    breadthFirstSearch(grid, colors, i, 0);
                if (colors[i][columns - 1] == WHITE)
                    breadthFirstSearch(grid, colors, i, columns - 1);
            }
            for (int i = 1; i < insideColumns; i++) {
                if (colors[0][i] == WHITE)
                    breadthFirstSearch(grid, colors, 0, i);
                if (colors[rows - 1][i] == WHITE)
                    breadthFirstSearch(grid, colors, rows - 1, i);
            }
            int islandCount = 0;
            for (int i = 1; i < insideRows; i++) {
                for (int j = 1; j < insideColumns; j++) {
                    if (colors[i][j] == WHITE) {
                        breadthFirstSearch(grid, colors, i, j);
                        islandCount++;
                    }
                }
            }
            return islandCount;
        }
    
        public void breadthFirstSearch(int[][] grid, int[][] colors, int row, int column) {
            int rows = grid.length, columns = grid[0].length;
            int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
            Queue<int[]> queue = new LinkedList<int[]>();
            colors[row][column] = GRAY;
            queue.offer(new int[]{row, column});
            while (!queue.isEmpty()) {
                int[] cell = queue.poll();
                int curRow = cell[0], curColumn = cell[1];
                for (int[] direction : directions) {
                    int newRow = curRow + direction[0], newColumn = curColumn + direction[1];
                    if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && colors[newRow][newColumn] == WHITE) {
                        colors[newRow][newColumn] = GRAY;
                        queue.offer(new int[]{newRow, newColumn});
                    }
                }
                colors[curRow][curColumn] = BLACK;
            }
        }
    }
    
    ############
    
    class Solution {
        private int m;
        private int n;
        private int[][] grid;
    
        public int closedIsland(int[][] grid) {
            m = grid.length;
            n = grid[0].length;
            this.grid = grid;
            int ans = 0;
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (grid[i][j] == 0) {
                        ans += dfs(i, j);
                    }
                }
            }
            return ans;
        }
    
        private int dfs(int i, int j) {
            int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0;
            grid[i][j] = 1;
            int[] dirs = {-1, 0, 1, 0, -1};
            for (int k = 0; k < 4; ++k) {
                int x = i + dirs[k], y = j + dirs[k + 1];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) {
                    res &= dfs(x, y);
                }
            }
            return res;
        }
    }
    
  • // OJ: https://leetcode.com/problems/number-of-closed-islands/
    // Time: O(MN)
    // Space: O(1)
    class Solution {
        int dirs[4][2] = { {0,1},{0,-1},{-1,0},{1,0} }, M, N;
        bool dfs(vector<vector<int>> &G, int x, int y, int id) {
            G[x][y] = id;
            bool ans = true;
            for (auto &[dx, dy] : dirs) {
                int a = x + dx, b = y + dy;
                bool oob = a < 0 || b < 0 || a >= M || b >= N;
                ans = ans && !oob;
                if (oob || G[a][b] != 0) continue;
                ans = dfs(G, a, b, id) && ans;
            }
            return ans;
        }
    public:
        int closedIsland(vector<vector<int>>& G) {
            int id = 2, ans = 0;
            M = G.size(), N = G[0].size();
            for (int i = 0; i < M; ++i) {
                for (int j = 0; j < N; ++j) {
                    if (G[i][j] != 0) continue;
                    if (dfs(G, i, j, id++)) ++ans;
                }
            }
            return ans;
        }
    };
    
  • class Solution:
        def closedIsland(self, grid: List[List[int]]) -> int:
            m, n = len(grid), len(grid[0])
            p = list(range(m * n))
    
            def find(x):
                if p[x] != x:
                    p[x] = find(p[x])
                return p[x]
    
            for i in range(m):
                for j in range(n):
                    if grid[i][j] == 1:
                        continue
                    idx = i * n + j
                    if i < m - 1 and grid[i + 1][j] == 0:
                        p[find(idx)] = find((i + 1) * n + j)
                    if j < n - 1 and grid[i][j + 1] == 0:
                        p[find(idx)] = find(i * n + j + 1)
    
            s = [0] * (m * n)
            for i in range(m):
                for j in range(n):
                    if grid[i][j] == 0:
                        s[find(i * n + j)] = 1
            for i in range(m):
                for j in range(n):
                    root = find(i * n + j)
                    if not s[root]:
                        continue
                    if i == 0 or i == m - 1 or j == 0 or j == n - 1:
                        s[root] = 0
            return sum(s)
    
    ############
    
    # 1254. Number of Closed Islands
    # https://leetcode.com/problems/number-of-closed-islands/
    
    class Solution:
        def closedIsland(self, grid: List[List[int]]) -> int:
            rows, cols = len(grid), len(grid[0])
            
            def dfs(i,j):
                if 0 <= i < rows and 0 <= j < cols and grid[i][j] != 1:
                    grid[i][j] = 1
                    
                    dfs(i, j-1)
                    dfs(i, j+1)
                    dfs(i-1, j)
                    dfs(i+1, j)
    
                    
            res = 0
            for i in range(rows):
                for j in range(cols):
                    if i == 0 or j == 0 or i == rows-1 or j == cols-1:
                        dfs(i,j)
    
            for i in range(rows):
                for j in range(cols):
                    if grid[i][j] == 0:
                        dfs(i,j)
                        res += 1
            
            
            return res
    
  • func closedIsland(grid [][]int) (ans int) {
    	m, n := len(grid), len(grid[0])
    	dirs := [5]int{-1, 0, 1, 0, -1}
    	var dfs func(i, j int) int
    	dfs = func(i, j int) int {
    		res := 1
    		if i == 0 || i == m-1 || j == 0 || j == n-1 {
    			res = 0
    		}
    		grid[i][j] = 1
    		for k := 0; k < 4; k++ {
    			x, y := i+dirs[k], j+dirs[k+1]
    			if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 {
    				res &= dfs(x, y)
    			}
    		}
    		return res
    	}
    	for i, row := range grid {
    		for j, v := range row {
    			if v == 0 {
    				ans += dfs(i, j)
    			}
    		}
    	}
    	return
    }
    

All Problems

All Solutions